简体   繁体   English

如何将sql的数据添加到组合框?

[英]How to add data for sql to combobox?

this code is working 该代码有效

TextBoxService is a combobox

Connection()
Dim sql As String
CON.Open()
DTS = New DataSet
sql = "SELECT * FROM Service"
dap = New SqlDataAdapter(sql, CON)
dap.Fill(DTS, "Service")
TextBoxService.DataSource = DTS.Tables("Service")
TextBoxService.DisplayMember = "ServiceName"
TextBoxService.ValueMember = "ServiceID"

because I need to at it to 2 comboboxes. 因为我需要2个组合框。 it will change both comboboxes when I selectd a combobox. 当我选择一个组合框时,它将同时更改两个组合框。 so i try to use this 所以我尝试用这个

bds = New BindingSource
DTS = New DataSet
bds.DataSource = DTS.Tables("Service")
TextBoxService.DataSource = bds
TextBoxService.DisplayMember = "ServiceName"
TextBoxService.ValueMember = "ServiceID"

but it show this error Cannot bind to the new display member 但显示此错误Cannot bind to the new display member

There is more than one way to this the easy and simple I find is if you 我发现,简单而简单的方法不只一种,如果您

*import the SQL data base in data sources *Select the table you want and set the object type eg( combobox, textbox or checkbox) *Then select eg combobox and click on the small arrow to the top left hand corner *Select you data source(table), display member(field name) * then go to the properties of the combobox object and select data binding plus sign * click on text and click the data source (table) and field you want to display the data from *在数据源中导入SQL数据库*选择所需的表并设置对象类型,例如(组合框,文本框或复选框)*然后选择例如组合框并单击左上角的小箭头*选择数据源(表),显示成员(字段名称)*然后转到组合框对象的属性,然后选择数据绑定加号*单击文本,然后单击要从中显示数据的数据源(表)和字段

You can also do it as 您也可以这样做

Declare SQLConnection Declare SQLDataReader Declare SQLCommand 声明SQLConnection声明SQLDataReader声明SQLCommand

Try
    If Con.State = ConnectionState.Closed Then
        Con.Open()

    cmd.Connection = Con
    cmd.CommandText = "Select field1, field2 from table"


    dr = cmd.ExecuteReader()

    ' Fill a combo box with the datareader
    Do While dr.Read = True
        ComboBoxName.Items.Add(dr.GetString(0))
        ComboBoxName.Items.Add(dr.GetString(1))
    Loop

    Con.Close()
    End If

Catch ex As Exception
    MsgBox(ex.Message)

End Try

Hope it works for you. 希望对你有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM