Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi all,
How bind a value from datatable to a combobox ?


*Form2
create a ColorCombobox
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.Items.Add(Color.Gray)
ComboBox1.Items.Add(Color.Green)
ComboBox1.Items.Add(Color.Red)
ComboBox1.Items.Add(Color.Blue)
ComboBox1.Items.Add(Color.Yellow)
ComboBox1.Items.Add(Color.White)
ComboBox1.Items.Add(Color.Black)
ComboBox1.Items.Add(Color.CornflowerBlue)
ComboBox1.Items.Add(Color.Firebrick)
ComboBox1.DrawMode = DrawMode.OwnerDrawFixed
End Sub

Private Sub ComboBox1_DrawItem(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles ComboBox1.DrawItem
e.DrawBackground()
Dim cmb As ComboBox = CType(sender, ComboBox)
Dim color As Color = CType(cmb.Items(e.Index), Color)
e.Graphics.FillRectangle(New SolidBrush(color), e.Bounds)
e.Graphics.DrawString(color.Name, e.Font, New SolidBrush(e.ForeColor), e.Bounds)
End Sub


* Form1

create a C1FlextGrid1

table have two columns
ID type int
Color type int or ...

Dim str as string ="select * from tablename where id="& C1FlextGrid1.rows(c1flextgrid1.rowsel).item(0) &"</pre>

*event
Private Sub C1FlextGrid1_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles C1FlextGrid1.MouseClick

binding value two columns ?

combobox1.selectindex=C1FlextGrid1.rows(1).item(1) don't work

Dim From2 As New Form2()
Form2.Show()
End Sub


any help from you
thanks a lot.!
Posted

1 solution

The following is the method to bind the combo box with a datatable and the values in the datatable are from the database.

VB
Dim sqlCon As New SqlConnection("server=yourserver;database=yourdeaabase;uid=sa;password=xxxx;")
Dim sqlDataAdapter As New SqlDataAdapter("select * from cState", sqlCon)
Dim dt As New DataTable()
sqlDataAdapter.Fill(dt)
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "StateName"
ComboBox1.ValueMember = "StateId"


The following code is without using any database tables
VB
Dim dt As New DataTable()
dt.Columns.Add("Id")
dt.Columns.Add("Value")
Dim i As Integer
For i = 1 To 10
    Dim dr As DataRow = dt.NewRow()
    dr.Item(0) = i.ToString()
    dr.Item(1) = i.ToString()
    dt.Rows.Add(dr)
Next
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "Value"
ComboBox1.ValueMember = "Id"
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900