Wednesday, 18 March 2009

Using ComboBox with DataTable in C#

Define the ComboBox with DataTable

//define DataTable
DataTable dt = new DataTable("dataTable");
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
//add DataRow
DataRow row = dt.NewRow();
row["Id"] = 1;
row["Name"] = "One";
dt.Rows.Add(row);
//assign to ComboBox
comboBox.DataSource = dt;
comboBox.DisplayMember = "Name";
comboBox.ValueMember = "Id";

Get Selected data from ComboBox

DataRow row = ((DataTable)comboBox.DataSource).Rows[comboBox.SelectedIndex];
int Id = (int)row["Id"];
string Name = (string)row["Name"];

2 comments:

Anonymous said...

good job

trimp said...

Is it possible to give more than one display member in cmbboBox.DisplayMember like:

cmbStaff.DisplayMember = string.Format("{0} {1} {2}","FirstName","MiddleName","LastName");

Post a Comment