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"];

Comments

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

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

    ReplyDelete

Post a Comment

Popular posts from this blog

Parse XML to dynamic object in C#

C# Crop white space from around the image