如何在sql select中使用变量作为字段名

时间:2013-12-17 22:53:39

标签: vb.net

我有这个代码的组合框

 headadaptor1 = New OleDbDataAdapter("SELECT code, fieldname FROM subject_1 ", cn)
    headcommand1 = New OleDbCommandBuilder(headadaptor1)
    headadaptor1.Fill(head1)
    TextBox6.Text = head1.Rows.Count
    'For i As Integer = 0 To head1.Rows.Count - 1
    '    Me.ComboBox2.Items.Add(head1.Rows(i)(1))
    'Next

    ComboBox2.DataSource = head1
    ComboBox2.ValueMember = "code"
    ComboBox2.DisplayMember = "fieldname"

来自另一个table1

我需要使用另一个表中的select命令取决于组合框选择值

select combobox2.selectedvalue.tostring from table2

提前致谢

1 个答案:

答案 0 :(得分:0)

如果您需要在组合框中选择的项目作为要从第二个表格中检索的列的名称,您可以在组合框的SelectedIndexChanged事件中编写此代码

If combobox.SelectedValue IsNot Nothing Then
    Dim drv = CType(combobox.SelectedItem, DataRowView)
    Dim cmdText = "SELECT " & drv.Row("fieldname").ToString & " FROM table2"
    Dim adapter = new OleDbDataAdapter(cmdText, cn)
    Dim table2 = new DataTable()
    adapter.Fill(table2)
End If