[2005] VB - Pass Selected ListView Item To Another Form
Hi All,
I have a listview which is populated via SQL. When I select the Item index, I was to open a form which will populate from SQL based on the selected item index.
e.g
VB Code:
Dim SQLSelect As String = "SELECT * FROM tblSuppliers WHERE [Supplier Code] = '" + lvwSuppliers.Items(lvwSuppliers.FocusedItem.Index).SubItems(0).Text + "' "
Any suggestions?
Re: [2005] VB - Pass Selected ListView Item To Another Form
Add a constructor to the form that takes a ListViewItem. When you create it you pass SelectedItems(0) from your ListView.
Re: [2005] VB - Pass Selected ListView Item To Another Form
Why take the entire listviewitem? Just take the index.
Re: [2005] VB - Pass Selected ListView Item To Another Form
After a bit more research, this is what I have come up with. It seems to work as expected.
Form 2:
VB Code:
Public Class Form2
Private SelectedListCode As String
Public Sub New(ByVal ListViewSelected As String)
MyBase.New()
InitializeComponent()
SelectedListCode = ListViewSelected
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MsgBox(SelectedListCode)
End Sub
End Class
Form1:
VB Code:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If ListView1.SelectedItems.Count <= 0 Then
MessageBox.Show("Item Not Selected")
Else
Dim f2 As New Form2(ListView1.SelectedItems(0).Text)
f2.ShowDialog()
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ListView1.Columns.Add("This Is A Column")
ListView1.Items.Add("Hello")
ListView1.Items.Add("GoodBye")
End Sub
End Class
Re: [2005] VB - Pass Selected ListView Item To Another Form
Quote:
Originally Posted by MaximilianMayrhofer
Why take the entire listviewitem? Just take the index.
Good point. I didn't really read the code so didn't see how it was being used.
I said to use the first SelectedItem, not the FocusedItem. They may or may not be the same object, depending on the circumstances. In your circumstances they are not.
Also, as Max says, there's no point passing more than you need. If all you need is the Text of the subitem then that's all you should be passing. Not the whole subitem.
Re: [2005] VB - Pass Selected ListView Item To Another Form
Updated Code in Post #4 :D
Re: [2005] VB - Pass Selected ListView Item To Another Form
Looks pretty good. To be safe you should test to make sure that there actually is an item selected before using the first selected item. If that code is executed before the user selects an item then an exception will be thrown.