使用Datatable和Listbox将变量传递给新表单

时间:2013-01-05 19:50:49

标签: vb.net

我目前正在尝试编写像地址簿这样的应用程序。列表框工作正常,它可以正确显示所有内容。但是我需要将所选列表框项的id传递给另一个表单。我在Form2中得到了这样的代码:

Private myTable As New DataTable()
Public Sub LoadXml(sender As Object, e As EventArgs) Handles Me.Load

    With myTable.Columns
        .Add("DisplayValue", GetType(String))
        .Add("HiddenValue", GetType(Integer))
    End With
    myTable.DefaultView.Sort = "DisplayValue ASC"

    ListBox1.DisplayMember = "DisplayValue"
    ListBox1.ValueMember = "HiddenValue"
    ListBox1.DataSource = myTable
    Dim doc As New Xml.XmlDocument
    doc.Load("c:\address.xml")
    Dim xmlName As Xml.XmlNodeList = doc.GetElementsByTagName("name")
    Dim xmlSurname As Xml.XmlNodeList = doc.GetElementsByTagName("surname")
    Dim xmlId As Xml.XmlNodeList = doc.GetElementsByTagName("id")
    For i As Integer = 0 To xmlName.Count - 1
        Dim nazwa As String = xmlName(i).FirstChild.Value + " " + xmlSurname(i).FirstChild.Value
        myTable.Rows.Add(nazwa, xmlId(i).FirstChild.Value)
        MsgBox(myTable.Rows(i).Item(1).ToString)
    Next i
    ListBox1.Sorted = True
End Sub

稍后在代码中我有事件:

Public Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick

End Sub

我想知道如何从DataTable中为选定的列表框项调用id。我希望你理解我的意思,因为我的英语并不完美:)

1 个答案:

答案 0 :(得分:0)

由于您已将XML值id添加到数据表列HiddenValue,并且已将HiddenValue指定为列表框的ValueMember,因此一旦选择了记录在列表框中,ID将在列表框的[SelectedValue][1]成员中可用。例如:

Public Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
    MsgBox("Selected Id: " & ListBox1.SelectedValue.ToString())
End Sub