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"];
good job
ReplyDeleteIs it possible to give more than one display member in cmbboBox.DisplayMember like:
ReplyDeletecmbStaff.DisplayMember = string.Format("{0} {1} {2}","FirstName","MiddleName","LastName");
You must create an expression Column
ReplyDeletedatatable.Columns.Add("FullName", typeof(string));
datatable.Columns[12345].Expression = "FirstName + ' ' + MiddleName + ' ' + LastName";