如何在VB.net中的combobox中从数据库中获取特定列的所有行?

时间:2012-10-07 14:33:33

标签: vb.net visual-studio-2010 ms-access-2007

这里我试图从组合框中的数据库中获取列 下面的代码导致组合框在组合框中有System.Data.DataViewManagerListItemTypeDescriptor 我的代码中缺少什么?

Imports System.Data
Imports System.Data.OleDb

Public Class Sales
    Private Const s As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\HOME\Desktop\Project\company\company\login.mdb"
    Public conn As OleDbConnection
    Public adapt As OleDbDataAdapter
    Public ds As DataSet
    Public tables As DataTableCollection
    Public table As DataTable
    Public rows As DataRowCollection
    Public row As DataRow
    Public cols As DataColumnCollection
    Public col As DataColumn
    Public sql As String
    Public isql, usql, dsql As String
    Public icmd, ucmd, dcmd As OleDbCommand
    Public p As OleDbParameter

    Private Sub Sales_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'LoginDataSet1.Login' table. You can move, or remove it, as needed.
        Me.LoginTableAdapter.Fill(Me.LoginDataSet1.Login)
        Try
            sql = "select cust_ID from Customer"
            conn = New OleDbConnection(s)
            adapt = New OleDbDataAdapter(sql, conn)
            ds = New DataSet
            conn.Open()

            adapt.Fill(ds, "ABC")
            ComboBox1.DataSource = ds
            ComboBox1.DisplayMember = "cust_ID"
            ComboBox1.ValueMember = "cust_ID"


            conn.Close()

        Catch ex As Exception

        End Try
    End Sub
End Class

1 个答案:

答案 0 :(得分:1)

DataSet包含DataTables,因此您需要

Dim connStr = "Data Source=.\SQLEXPRESS;Initial Catalog=testing;Integrated Security=true;"
Dim sql = "SELECT str FROM testTable"
Dim da = New SqlDataAdapter(sql, connStr)
Dim ds = New DataSet
da.Fill(ds)
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.DisplayMember = "str"
ComboBox1.ValueMember = "str"

但直接使用DataTable更简单:

Dim connStr = "Data Source=.\SQLEXPRESS;Initial Catalog=testing;Integrated Security=true;"
Dim sql = "SELECT str FROM testTable"
Dim da = New SqlDataAdapter(sql, connStr)
Dim dt = New DataTable
da.Fill(dt)
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "str"
ComboBox1.ValueMember = "str"

当然,您将使用我使用的SqlWhatever命令的OleDbWhatever等价物。