使用ListBox中的值构造字符串

时间:2017-04-10 14:29:12

标签: vb.net

我想在从列表框中选择项目时填充数据网格视图。

我的代码给了我这个错误:

  

运营商'&'未定义为字符串" SELECT DeptName FROM Department"并键入' DataRowView'。

这是我的代码:

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
    cmd = New OleDbCommand("SELECT DeptName FROM  Departments inner  JOIN Faculties ON Faculties.ID = Departments.FacID where FacID='" & ListBox1.SelectedValue & "'", conn)
    Dim daa As New OleDbDataAdapter(cmd)
    Dim dtt As New DataTable
    daa.Fill(dtt)
    dgv.DataSource = dtt
End Sub

2 个答案:

答案 0 :(得分:1)

有几种方法可以看这个。

您可以事先在ValueMember上设置ListBox1以下是ListBox的值为1到10及其正方形的示例。 ValueMember是FacID,只是数字。 DisplayMember是FacID的平方(用于演示目的!),表明您不需要显示值成员。

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim i As Integer
    Dim table As New DataTable()
    Dim column1 As New DataColumn("FacID")
    Dim column2 As New DataColumn("Square")
    table.Columns.Add(column1)
    table.Columns.Add(column2)
    For i = 0 To 9
        Dim row As DataRow = table.NewRow()
        row("FacID") = i
        row("Square") = i ^ 2
        table.Rows.Add(row)
    Next i
    Dim view As New DataView(table)
    ListBox1.DataSource = view
    ' set the DisplayMember and ValueMember
    ListBox1.DisplayMember = "Square"
    ListBox1.ValueMember = "FacID"
End Sub

Private Sub ListBox1_SelectedValueChanged(sender As Object, e As EventArgs) Handles ListBox1.Click
    Dim message = "Selected value: " & ListBox1.SelectedValue.ToString()
    MessageBox.Show(message)
End Sub

这就是ListBox在运行时的样子

enter image description here

单击时,显示所选值的消息

如果在运行您提供的代码之前完成此操作,那么您几乎可以按原样使用代码,因为现在ListBox1.ValueMember是一个整数。注意,您应该更严格并将整数转换为字符串以准备查询。

Dim query =
    "SELECT DeptName FROM Departments " &
    "inner JOIN Faculties ON Faculties.ID = Departments.FacID " &
    "where FacID = '" & ListBox1.SelectedValue.ToString() & "'"

你也可以设置ValueMember 。如果未指定ValueMember,则SelectedValue默认为DataSource中的类型,即DataView,并且出于所有意图和目的,IList } DataRowView

没有DisplayMember,ListBox看起来像这样

enter image description here

我认为它不是这样的。所以只需事先设置ValueMember,你应该全部设置。

答案 1 :(得分:0)

user1ListBox1.SelectedValue,因此您无法将其添加到字符串中。你可能想要这样的东西:

DataRowView

或者

"SELECT DeptName FROM  Departments inner  JOIN Faculties ON Faculties.ID = Departments.FacID where FacID='" _
     & ListBox1.SelectedValue["yourColumn"].ToString() & "'"