How to get selected items from listbox from vb.net - vb.net

I'm using ListBox to display some value, it works properly but when I am trying to get the selected item from the list box it shows an error null reference error.
Below is my code that I have written to get values from ListBox:
For i As Integer = 0 To lsttasks.SelectedItems.Count - 1
userTaskDtlSrNo = Val(lsttasks.SelectedItems(i).ToString())
If userTaskDtlSrNos <> "" Then userTaskDtlSrNos &= ","
userTaskDtlSrNos &= userTaskDtlSrNo
Next
Can anyone tell me what's wrong with this code?

You don't need the Val() function there
Don't forget to declare Dim userTaskDtlSrNo as String
Use: userTaskDtlSrNo = lsttasks.SelectedItems(i).ToString()

I believe your assigning a string to a integer,
declare userTaskDtlSrNo as String, then use
userTaskDtlSrNo = Val(lsttasks.SelectedItems(i).ToString())
if you need to change userTaskDtlSNo to an integer after then just use
Dim intUserTask As Integer
Integer.TryParse(userTaskDtlSrNo, intUserTask)
to assign a new variable with same value as an integer, i dont know the rest of your code but i see no reason why this would not solve your problem. :-)

This can be way easier than it looks.
If you want to delete an object that is selected:
'let recips be the listbox name
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Recips.Items.Remove(Recips.SelectedItem)
End Sub
If you want to get the selected item (like for setting it to a string):
'let pie be a string variable, and recips to be the listbox again respectively
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
pie = Recips.selectedItem
End Sub
I hope this was enough for you, I'm not sure if I covered on enough information. Please comment so, if I forgot. Accept this answer if this helped.

Related

How to pass ListBox selected item into file?

What I have:
Private Sub ChooseProgram_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChooseProgram.SelectedIndexChanged
Dim curItem As String = ChooseProgram.SelectedItem.ToString()
End Sub
Private Sub Install_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Install.Click
Dim jhin As System.IO.StreamWriter
jhin = My.Computer.FileSystem.OpenTextFileWriter("C:\Temp\jhin.bat", True)
jhin.WriteLine("$program = " & curitem.string")
jhin.Close()
End Sub
I just want to write the string into the file.
How is that possible?
Thx for ur help!
Hannir
UPDATE:
' Ensure an item is selected
If ChooseProgram.SelectedItem Is Not Nothing Then
curItem = ChooseProgram.SelectedItem.ToString()
End If
I get an error here.
"The Is operator does not accept operands of type " integer " . The operands must be reference types, or permit types , NULL values ​​."
Really thx for ur quick help! #Pro Grammer
If you just click Install, and nothing is selected, it ends in an error. So is it possible to say "You need to select an item before" or the Install button is just clickable when selected an item?
For starters you have to move the declaration of the curItem variable out of the SelectedIndexChanged method, to what's called Class level.
As it stands your variable is accessible within your SelectedIndexChanged method only, whereas if you move it to class level it will be accessible by everything within that class (the class in this case is your Form). You then just modify the variable from your SelectedIndexChanged method.
Dim curItem As String = "" 'We'll start with an empty string.
Private Sub ChooseProgram_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChooseProgram.SelectedIndexChanged
curItem = ChooseProgram.SelectedItem.ToString()
End Sub
Now you will be able to access the variable from your button and write it to a file.
The last thing you have to do is to close the StreamWriter that you create so that it will release the lock on the file. The easiest and best way to do so is wrapping it in an Using/End Using block.
Private Sub Install_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Install.Click
Using jhin As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter("C:\Temp\jhin.bat", True)
jhin.WriteLine("$program = " & curItem)
End Using
End Sub
EDIT:
To make your button clickable only when an item is selected, first set the button's Enabled property to False via the Property Window in the designer, then use this code in the SelectedIndexChanged event:
Install.Enabled = ChooseProgram.SelectedIndex >= 0
If ChooseProgram.SelectedIndex < 0 Then Return
curItem = ChooseProgram.SelectedItem.ToString()
This is one option:
Private Sub Install_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Install.Click
Dim curItem as String = ""
' Ensure an item is selected
If ChooseProgram.SelectedItem IsNot Nothing
curItem = ChooseProgram.SelectedItem.ToString()
End If
' Double checking valid input
If String.IsNullOrWhiteSpace(curItem) Then
' Handle empty input - Display message, etc
' Exit Sub (unless bat handles empty)
End If
Dim jhin As System.IO.StreamWriter
jhin = My.Computer.FileSystem.OpenTextFileWriter("C:\Temp\jhin.bat", True)
jhin.WriteLine("$program = " & curItem)
jhin.Close()
End Sub
Instead of using the ChooseProgram_SelectedIndexChanged event, you can deal with it from here, since you aren't performing any other actions in that method. If you wanted to still use that event, you would assign the string value into a field which could be accessed across the class. Check out Visual Vincent's answer for this example, and also of a Using block, which removes the need to call jhin.Close() manually and also provides a much clearer format

vb.net string lookup in listbox with output as different part of the string

Last Name Finder
what I'm trying to do is create a list of all peoples surnames where the 1st name = #name
although this isn't the exact purpose its easier to try and explain the actual content. i'm aware it may be easier to use a data source, but I want to try and avoid that where possible.
Form_Load
ListBox1.Items.Add("Dean Smith")
ListBox1.Items.Add("John Jones")
ListBox1.Items.Add("David Johnson")
ListBox1.Items.Add("Samantha Thompson")
ListBox1.Items.Add("Claire Frost")
ListBox1.Items.Add("John Brown")
and then some sort of string manipulation to do the following on button_click
if textbox1.text contains "John" then
listbox2.items.add(Jones)
listbox2.items.add(Brown)
else messagebox.show("No matches found")
end if
Thanks for any input.
What I've understood is that you are willing to use your textbox as a filter to the listbox. And this can be achieved by running the query to your db on every TextChanged().
So to give you some guidelines, you can proceed like this;
private Names As List(Of String)
Private Sub Form2_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Names = New List(Of String)
With Names
.Add("Dean Smith")
.Add("John Jones")
.Add("John Brown")
End With
For Each Name As String In Names
ListBox1.Items.Add(Name)
Next
End sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
ListBox1.Items.Clear()
For Each s As String In Names
If s.Substring(0, TextBox1.Text.Length).ToLower = TextBox1.Text.ToLower Then
ListBox1.Items.Add(s)
End If
Next
End Sub
I hope this solution might help you achieve what you wanted. You can also apply direct filter to the List by using a delegate function, which will avoid you from looping again on TextChange().

Vb.net dims in buttons turning to 0

I have this snippet from my code
Private Sub BtnOne_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnOne.Click
Dim ownerNum As Integer 'sets variable
ownerNum = Ownerfnc(Indicatorbtn, ownerNum) 'gives variable a number
End Sub
Function cntOwner(ByRef indicator As Object, ByRef old As Integer) As Integer
If indicator.FillColor = Color.Transparent Then
indicator.FillColor = Color.green
Return player
Else
Return old
End If
End Function
when i click the button it sets the variable to the correct number but if i click it again it sets it back to 0 is there a way to stop it from doing it?
Thanks
Declare your variable globally (outside procedure) to persist it's value.
At the moment, your variable declared locally within procedure. That way it will be recreated -hence get reset to default value- every time the procedure called. For reference, read this : MSDN - Scope in Visual Basic.
Thanks for the answers, needed to explain a bit more that i have 42 different variables that where in 42 different button clicks.
The answer was to just put static instead of dim and that worked fine for anyone that was looking for a solution like this
you should declare your variable outside the events of button click. every time you you click the button the value of ownerNum is reseting. try dis code
Dim ownerNum As Integer 'sets variable
Private Sub BtnOne_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnOne.Click
'now every time you click the ownerNum is not reseting.
ownerNum = Ownerfnc(Indicatorbtn, ownerNum) 'gives variable a number
End Sub
Function cntOwner(ByRef indicator As Object, ByRef old As Integer) As Integer
If indicator.FillColor = Color.Transparent Then
indicator.FillColor = Color.green
Return player
Else
Return old
End If
End Function

Validate only newly typed text

I'm making simple application. There is a textbox and a ListBox. When user type something in the textbox, that text add to the ListBox split by space after some validation process. I done it. Here is my code.
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
'split by space
Dim arrText() As String = Split(TextBox1.Text, " ")
ListBox1.Items.Clear()
'ValidateText is a function
For i = 0 To UBound(arrText)
ListBox1.Items.Add(ValidateText(arrText(i)))
Next i
End Sub
But I want to upgrade it because the validation process take more time. When user type something in the textbox need to do the same process but for only newly typed text. (From the cursor position forward to the end of the text) already validated text doesn’t need to validate again. I think someone can help.
Note: user can be also copy & paste words in the textbox
Thank in advance
I have found a solution thanks to lapheal who member in msdn forum
Private validatedDic As New Dictionary(Of String, String) 'or Dictionary(Of String, Object)?
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
'split by space
Dim arrText() As String = Split(TextBox3.Text, " ")
ListBox1.Items.Clear()
'ValidateText is a function
For i = 0 To UBound(arrText)
Dim text As String = String.Empty
If Not validatedDic.TryGetValue(arrText(i), text) Then
text = ValidateText(arrText(i))
validatedDic(arrText(i)) = text
End If
ListBox1.Items.Add(text)
Next i
End Sub

visual basic :Help removing items from listbox

I have to make a listbox with a few(8) names in it & double clicking on a name in the listbox will removed the name from it.
I have already add the names into the form using the listbox.items.add method & would display the names in it.
Then I enter the coding for 8 names in double_click procedure(listbox) using the "listbox.items.remove" method.
However, when i try double clicking on a name in the listbox, it would remove all the names instead.
What coding do i need? help appreciated!
Option Strict On
Option Explicit On
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ListBox1.Items.Clear()
ListBox1.Items.Add("1")
ListBox1.Items.Add("2")
ListBox1.Items.Add("3")
ListBox1.Items.Add("4")
ListBox1.Items.Add("5")
ListBox1.Items.Add("6")
ListBox1.Items.Add("7")
ListBox1.Items.Add("8")
End Sub
Private Sub ListBox1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.DoubleClick
Dim i As Integer = ListBox1.SelectedIndex
If i >= 0 And i < ListBox1.Items.Count Then
ListBox1.Items.RemoveAt(i)
End If
End Sub
End Class
if you are looking at dynamic deletion of items, i think you should check out Jquery,Ajax,DOM
there are a couple of nice tutorials that would help you with that. i just came across this one and found it interesting
http://www.satya-weblog.com/2010/02/add-input-fields-dynamically-to-form-using-javascript.html