• 0

[VB.NET]Listbox string replace


Question

First of all Happy New Year Neowins.

The program gets the following string in db.lib NAME > URL

For Example:


GOOGLE > http://google.com
[/CODE]

When i start my form loads the whole db.lib file in listbox1 like this:

listbox.png

after that when i double click it will open me http://google.com because i split it with this tag (">")

[CODE]
Dim arg() As String
For i As Integer = 0 To ListBox1.Items.Count
arg = ListBox1.SelectedItem.ToString.Split(">")
Next
[/CODE]

My question is: How can i hide the url addres ("http://") in list box to show only the name Google and when i click it to open http://google.com - Thanks

Btw this program gets the mms: protocol (most used for Online TV) and play it in VLC player.

The whole code:

[CODE]
Imports System.Net
Imports System.IO
Imports System.Web
Public Class Form1
Dim i As Integer
Private Sub ??????ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ??????ToolStripMenuItem.Click
Dim inp As String = InputBox("???? ??? ??????????", "???????", vbOKCancel)
If inp <> "" Then
ListBox1.Items.Add(inp)
End If
End Sub
Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
My.Settings.path = Label1.Text
Dim w As New System.IO.StreamWriter("db.lib")
Dim i As Integer
For i = 0 To ListBox1.Items.Count - 1
w.WriteLine(ListBox1.Items.Item(i))
Next
w.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label1.Text = My.Settings.path
Dim r As New System.IO.StreamReader("db.lib")
While (r.Peek() > -1)
ListBox1.Items.Add(r.ReadLine)
End While
r.Close()
End Sub
Private Sub ListBox1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.DoubleClick
Dim Client As New WebClient
Dim arg() As String
For i As Integer = 0 To ListBox1.Items.Count
arg = ListBox1.SelectedItem.ToString.Split(">")
Next
Try
Dim html = Client.DownloadString(New Uri(arg(i + 1)))
Client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)")
Try
Dim StartPos As Integer = html.IndexOf("mms")
Dim EndPos As Integer = html.IndexOf("</object>", StartPos)
Dim finaloutcome As String = html.Substring(StartPos, EndPos - StartPos)
Dim Key As String = (finaloutcome.Substring(0, 90))
Dim Last As String = Key.Replace(""">", "")
Dim all As String = Last.Replace("<pa", "")
If Label1.Text = "" Then
MsgBox("Please coose the folder to your VLC Player!")
Else
Shell(Label1.Text & "\vlc.exe " & all)
End If
Catch ex As Exception
MsgBox("This link does not support mms protocol!")
End Try
Catch ex As Exception
MsgBox("I cant connect to the website!")
End Try
End Sub
Private Sub VLCPlayerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VLCPlayerToolStripMenuItem.Click
FolderBrowserDialog1.ShowDialog()
Label1.Text = FolderBrowserDialog1.SelectedPath
My.Settings.path = Label1.Text
My.Settings.Save()
End Sub
End Class
[/CODE]

Link to comment
https://www.neowin.net/forum/topic/1128630-vbnetlistbox-string-replace/
Share on other sites

16 answers to this question

Recommended Posts

  • 0

You could have an array of all your sites that when clicked in the list it goes to that index and launches the site that's in that index. So what you would end up doing, is dump the db.lib thing into an array (splitting at the > and grabbing the second index) and at the same time put the first split index into the list box.

Then have a Click, or Selected Index Changed event. And just do like:

LaunchSite(siteUrls[lstSites.SelectedIndex]) 'Replacing functions/names accordingly

  • 0

I think what Firey means is to create a class member that is an array, and keep your URLs in there separately. So in your class you'd do this (please note, my VB is very rusty, so this will probably not compile, but it should give you an idea as to what to do):

Imports System.Net
Imports System.IO
Imports System.Web
Imports System.Collections.Generic

Public Class Form1
	Private m_urls As List(Of String)

	' We'll use this subroutine to add the site to both the listbox and the list of URLs.
	Private Sub AddSiteToList(ByVal siteString As String)
		Dim stringParts() As String = str.Split("&gt;")

		If stringParts.Length &lt;&gt; 2 Then
			Throw New ArgumentException("Parameter 'siteString' was an unexpected format (value: '" + siteString + "'). Please make sure string is of the format '[Site_Name]&gt;[URL]'")
		End If

		ListBox1.Items.Add(stringParts(0))
		m_urls.Add(stringParts(1))
	End Sub

	' We'll use this function to retrieve the URL for the selected item.
	Private Function GetSelectedUrl() As String
		If ListBox1.SelectedIndex &gt; -1 Then
			GetSelectedUrl = m_urls(ListBox1.SelectedIndex)
		Else
			GetSelectedUrl = ""
		End If
	End Function

	Private Sub ??????ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ??????ToolStripMenuItem.Click
		Dim inp As String = InputBox("???? ??? ??????????", "???????", vbOKCancel)
		If inp &lt;&gt; "" Then
				AddSiteToList(inp)
		End If
	End Sub


	Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
		My.Settings.path = Label1.Text
		Dim w As New System.IO.StreamWriter("db.lib")
		For i As Integer = 0 To ListBox1.Items.Count - 1
			w.WriteLine(ListBox1.Items.Item(i) + "&gt;" + m_urls(i))
		Next
		w.Close()
	End Sub

	Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
		Label1.Text = My.Settings.path
		Dim r As New System.IO.StreamReader("db.lib")
		While (r.Peek() &gt; -1)
				AddSiteToList(r.ReadLine)
		End While
		r.Close()
	End Sub

	Private Sub ListBox1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.DoubleClick
		Dim url As String = GetSelectedUrl()

		If url.Length &gt; 0 Then
			Try
				Dim Client As New WebClient
				Dim html = Client.DownloadString(New Uri(url))
				Client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)")
				Try
					Dim StartPos As Integer = html.IndexOf("mms")
					Dim EndPos As Integer = html.IndexOf("", StartPos)
					Dim finaloutcome As String = html.Substring(StartPos, EndPos - StartPos)
					Dim Key As String = (finaloutcome.Substring(0, 90))
					Dim Last As String = Key.Replace("""&gt;", "")
                                        Dim all As String = Last.Replace("&lt;pa", "")
					If Label1.Text = "" Then
						MsgBox("Please coose the folder to your VLC Player!")
					Else
						Shell(Label1.Text &amp; "\vlc.exe " &amp; all)
					End If
				Catch ex As Exception
					MsgBox("This link does not support mms protocol!")
				End Try
			Catch ex As Exception
				MsgBox("I cant connect to the website!")
			End Try
		End If
	End Sub

	Private Sub VLCPlayerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VLCPlayerToolStripMenuItem.Click
		FolderBrowserDialog1.ShowDialog()
		Label1.Text = FolderBrowserDialog1.SelectedPath
		My.Settings.path = Label1.Text
		My.Settings.Save()
	End Sub
End Class

  • 0

Personally, I'd have them split on reading from the db.lib file into a key/value pair with the DisplayMember property of the list box set to the key (name of site) and the ValueMember property of list box set to the value (the url) then assign the collection of key/value pairs to the listbox items collection...

Really can't be bothered to write up a sample though...

  • 0

Personally, I'd have them split on reading from the db.lib file into a key/value pair with the DisplayMember property of the list box set to the key (name of site) and the ValueMember property of list box set to the value (the url) then assign the collection of key/value pairs to the listbox items collection...

Really can't be bothered to write up a sample though...

That probably would be better, but I picked the easiest solution requiring the fewest changes :p

  • 0

That probably would be better, but I picked the easiest solution requiring the fewest changes :p

Well, should also note it'd be more ideal to move any non-UI code out of the Form class into it's own class(es) too... so may as well re-architect it a little more anyway... *shrugs*

  • 0

Not for the sake of < 100 LoC it wouldn't. KISS.

Right, I agree with KISS - however this looks like an educational application (as in one he's working on to learn rather than just a quick fix from someone who knows concepts); in which case I deem it more useful to practice correctly laying out your code as you would for a larger application.

Once people get set in lazy ways they tend to stay in them.

  • 0

I agree that in general code should be split out as much as possible (Gui with Gui, logic with logic). Though he doesn't seem to have strong knowledge with the programming, so it would end up just causing more headaches to go and re-do all his code for him. As he won't understand what the program does.

  • 0

best of using a listbox tag of your item for the url and open the tag keeping the item intact.

listbox.Items(i).Tag = "http://www.google.com"[/CODE]

Indeed that would be better. In my defence the last time I used a ListBox in Windows Forms .NET 3 hadn't gained any traction yet :p

This topic is now closed to further replies.
  • Posts

    • This whole dumb age verification thing needs to die and be replaced by giving parents tools to control devices. Why am I required to plaster my ID all over the internet to prove I'm old enough when parents should be the ones dictating what their kids are doing on their phones. Apple released great set of tools for iPhones coming to iOS 27 that do just that. Why are governments not mandating that kind of control to phone makers to built them into phones. This whole thing is so absolutely idiotic it's wild.
    • Remeber this decade, when the free internet died... tell your grand kids about this, record there reaction and post it on InstaTwitBook.com
    • UK nudity blockers are a looming privacy disaster, we must be able to see the source code by Paul Hill Image via Pexels The UK government, just like many state governments in the US and national governments around the world, has begun going on a bit of a power trip when it comes to digital safety. The major step taken so far is the introduction of the Online Safety Act, which requires users to prove their age to access adult websites (it includes more than this, too). Now, UK PM Keir Starmer is calling on Apple and Google, and presumably other mobile OS makers, to scan phones for explicit images to protect children. This potentially mandatory on-device scanning by vendor-controlled software will create unacceptable harms to individual freedoms and transparency, and introduce massive surveillance risks. In a statement on June 8, the Prime Minister stated that big tech companies, such as Apple and Google, must add features to their platforms, such as iOS and Android, that will detect and block sexually explicit or nude images involving under-18s on phones or tablets. Adults who want to take or send nudes would be required to hand over some form of identification to stop their phone from blocking these pictures, creating unnecessary privacy risks. According to the government, it wants to see these measures implemented within three months; otherwise, the government will introduce legislation to force them to introduce such technology. The legislation will include fines for companies and maybe even criminal liability for tech bosses who do not comply with the measures. In its announcement, the government said that stopping users from taking, sending, or receiving nudes without verifying their age is technically feasible, and pointed to a British firm called SafeToNet, which has made proprietary, closed-source, uninstallable software called HarmBlock and is actively selling a device with it enabled and is working with other OEMs. The fact that this software is closed source is a huge problem because it’s a black box; you do not know what it is doing on your device. The fact that it is unremovable is also a problem because you lose control of a phone that you own. Laughably, the government, just before highlighting SafeToNet, says that companies must introduce such measures “without threatening privacy or collecting any data.” It then says over-18s will still be able to view adult content by providing proof of age… Which sounds to me like data collection. SafeToNet makes some debatable claims about HarmBlock The government’s example software, HarmBlock, is a hugely alarming choice to espouse the virtues of this type of software. SafeToNet claims that HarmBlock is “ethically developed,” but this is the opposite of the truth. This black box software puts digital handcuffs on you if it’s installed in your device, taking away your freedom to control what software runs on your device, as it cannot be removed. It is not even free software, so we cannot inspect the source code to see what it is doing. For all we know, it could be acting maliciously. While that’s unlikely, we can’t verify that it’s not doing that. When Google and Apple do inevitably integrate these features on devices in the UK, they are very likely to be closed-source binaries, which will also be non-auditable. They will also have identity services built into them, which will require at least temporary collection of sensitive identity documents to verify your age. One saving grace for Android users is that this nudity blocker will very likely be implemented within the Google Play infrastructure that’s deeply tied into commercial Android devices. However, anyone with enough determination to throw out Google apps from their phone by flashing a custom ROM could find they regain control over their phone again without these digital handcuffs. Obviously, this is only how I expect Google to implement the feature; if it bakes it into the open-source Android somehow, that would be bad news for anyone looking to escape it. Outside of stripping mobile phone users of their freedom and sovereignty over their devices, these proprietary on-device machine learning or hash-matching solutions cannot be independently audited. This means that hackers could potentially exploit them because security researchers can’t investigate the code, and they could overstep their intended use case and collect even more user data without anybody knowing. We also wouldn’t know if the code is prone to detecting false positives or biased classification, because we can’t see the code. In the government’s announcement, contributing comments from the Internet Watch Foundation keep talking about “on-device protections” as if to say that users don’t need to worry about server-side processing; however, this is misleading, as data could flow from devices for the purpose of updates, remote model changes, telemetry, or server-side matching. We’ve also seen with the Online Safety Act that the government is never content with the laws it introduces; it always wants to expand the controls. If this scanning functionality arrives on devices, it might only block nudes initially, but later governments could pressure vendors for expanded access or use mandated features for other surveillance aims. The introduction of on-device scanners opens the door to massive risks in the future. Once nude blocking becomes normalized, regulators like Ofcom or politicians themselves could push for more controls over people’s devices. Very possible candidates for blocking include hate speech, misinformation, or undesirable political content. Also, there is a chance that once Apple and Google have developed this software, they might attempt to reuse the infrastructure for commercial or foreign requests, putting customers in greater danger. Just the UK's demand for this sets a precedent. What if a dictatorship decides to spy on activists by demanding that Google or Apple implement similar controls? Another concern with this scanning is that it adds compliance costs for businesses looking to get into the mobile operating system space. While Google and Apple dominate the space right now, there are lots of smaller companies creating mobile operating systems too, including community projects with very shallow pockets. How are these smaller competitors supposed to implement sophisticated nudity detectors? Simply put, they can’t. Then the government goes after them, causes them to shut down, and Google and Apple have less competition. Image via Aurora Store For us users who value sovereignty over our technology, this development will force us to seek freedom-respecting alternatives. The simplest path forward will likely be to install a custom ROM on an Android device; however, kicking Google off the phone with its black box nudity blocker could also make it harder to access apps such as banking apps, which tend to need you to pass Google's integrity checks. Thankfully, Google Play Store apps can still be obtained by storefronts such as the Aurora Store, but it just adds to the friction. To be fair to those pushing this measure to protect children, I think it will be reasonably effective, but people will still try to find ways around it, just as they’ve done with age gates on adult websites introduced under the Online Safety Act. In the effort to find circumvention methods, it could lead users to join riskier platforms that introduce new dangers. This effort also diverts resources from proven interventions such as law enforcement cooperation, targeted investigations, education, and support services to broad technical controls that have uncertain effectiveness (due to their newness). If the government is set on introducing such tools, then there ought to be safeguards in place. Any mandated code should be released as free software so that it can be audited, and the binaries should be reproducible builds so that the public knows nothing has been tampered with in the code used to create the binaries shipped out. Ideally, these tools should also be voluntary, opt-in, and even community-run. This would also allow people to have full control over their hardware while allowing parents to flip a switch to turn on these protections for children, with the knowledge that the code being run is doing exactly what it says on the tin, and nothing nefarious, like a black box solution could be doing. The government should also have a narrow legal scope where this technology stays with blocking nudes and not spreading to blocking political opinions, hate speech, and so on. Ideally, any implementation should avoid identity-linked age verification to keep user data safe, and matching should be done locally with no server telemetry to ensure it is truly on-device. While I do understand that stakeholders such as parents want to keep children safe, the potential for abuse with this type of software is colossal. It would entrench black-box surveillance and take away our freedom to use our devices as we want. There is also the acute risk that the government will demand this surveillance be expanded to block other activities, which could be particularly dangerous. If you are in the UK and don’t wish to see these measures implemented, it is still possible to write to your MP, which could lead to some better safeguards being introduced before it’s too late. Once we get more technical information about how this will be implemented, then we will be able to see if de-Googling Android devices will bypass this measure. For anyone with an iPhone, there is zero chance that you’ll be able to take off these handcuffs because Apple doesn’t let you mess with your software.
    • I'm reading the reports as EU rejecting Apple's proposal because Trusted System Agent would be an intermediary offered to third party AI's (this article is also worded as such) but Siri AI itself would not pass this intermediary. This would cause a situation where Siri AI would have more direct system access and offer it an unfair advantage. (speaking from EU regulator perspective here) Apple is citing security issues with doing what EU asked for, and I think this also supports this theory, because truly direct system access like Siri AI would make it impossible to control third party AI's running on the devices and e.g. reign them in via adjustments to Trusted System Agent. So, I _think_ this is the sticking point right now: EU saying they need to be on equal footing as Siri AI, Apple saying they can't be because Apple only trusts their own AI. Apple could of course be leaning a bit extra hard towards this because they're biased in terms of excluding competitors. One method to find an agreement would be to have Siri AI also run through Trusted System Agent and treat it as untrusted. This kind of defensive architecture design (especially when involving an AI) would honestly not be a very bad idea from a sheer engineering standpoint. But then Apple would need to swallow their pride and adapt worldwide due to EU, and make perhaps major updates delaying Siri AI once more.
  • Recent Achievements

    • Very Popular
      Captain_Eric earned a badge
      Very Popular
    • One Month Later
      amusc earned a badge
      One Month Later
    • One Month Later
      DJC50PLUS earned a badge
      One Month Later
    • Week One Done
      DJC50PLUS earned a badge
      Week One Done
    • Proficient
      Eric Biran went up a rank
      Proficient
  • Popular Contributors

    1. 1
      +primortal
      511
    2. 2
      PsYcHoKiLLa
      220
    3. 3
      ATLien_0
      92
    4. 4
      +Edouard
      90
    5. 5
      Steven P.
      83
  • Tell a friend

    Love Neowin? Tell a friend!