如何将数据库显示到组合框中

时间:2013-10-01 09:14:36

标签: vb.net

我在组合框中得到错误,而组合框显示数据库...它在里面显示了combobox.text =“System.Data.DataRowView”。

Private Sub FillCombo()
Try
    conn = New OleDbConnection(Get_Constring)
    Dim sSQL As String = ("SELECT subject FROM student order by subject")
    Dim da As New OleDbDataAdapter(sSQL, conn)
    Dim ds As New DataSet
    da.Fill(ds)
    cmbsection.ValueMember = "ItemName"
    cmbsection.DataSource = ds.Tables(0)
    cmbsection.SelectedIndex = 0
Catch ex As Exception
    MsgBox("ERROR : " & ex.Message.ToString)
End Try

End Sub

5 个答案:

答案 0 :(得分:0)

我认为这是在Valuemember之前设置数据源的一个简单例子。

cmbsection.DataSource = ds.Tables(0)
cmbsection.ValueMember = "ItemName"

答案 1 :(得分:0)

试试这个

Private Sub FillCombo()
Try
   conn = New OleDbConnection(Get_Constring)
   Dim sSQL As String = ("SELECT subject FROM student order by subject")
   Dim da As New OleDbDataAdapter(sSQL, conn)
   Dim ds As New DataSet
   da.Fill(ds)
   cmbsection.ValueMember = "ItemName"
   cmbsection.DataSource = ds;
   cmbsection.SelectedIndex = 0;
Catch ex As Exception
   MsgBox("ERROR : " & ex.Message.ToString)
End Try

答案 2 :(得分:0)

 Private Sub FillCombo()
Try
    conn = New OleDbConnection(Get_Constring)
    Dim sSQL As String = ("SELECT subject FROM student order by subject")
    Dim da As New OleDbDataAdapter(sSQL, conn)
    Dim ds As New DataSet
    da.Fill(ds)
cmbsection.Items.clear
For i as Integer = 0 to ds.Tables(0).rows.count-1
    cmbsection.Items.add( ds.Tables(0).rows(i).item("subject").tostring)

next

Catch ex As Exception
    MsgBox("ERROR : " & ex.Message.ToString)
End Try
End Sub

答案 3 :(得分:0)

您需要设置

cmbsection.DisplayMember = "Subject"
cmbsection.ValueMember = "Subject"

答案 4 :(得分:0)

Public Sub LoadProvince()
    Dim cn As New SqlConnection("server=.\LENOVO;uid=sa;pwd=123;database=SchoolDb;")
    cn.Open()

    Dim cmd As New SqlCommand("SELECT * FROM Product;", cn)
    Dim dr = cmd.ExecuteReader()

    Dim dt As New DataTable()
    dt.Load(dr)
    dr.Close()

    cboPROVINCE.DisplayMember = "Product_NAME"
    cboPROVINCE.ValueMember = "Product_Id"
    cboPROVINCE.DataSource = dt
End Sub