How to display multiple values in a combo box from a datatable
16,921
Solution 1
I have done it as under
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Col1", typeof(string));
dt.Columns.Add("Col2", typeof(string));
dt.Columns.Add("ConcatenatedField", typeof(string), "Col1 + ' : ' +Col2");
Enumerable.Range(1, 10).ToList().ForEach(i => dt.Rows.Add(i, string.Concat("Col1", i), string.Concat("Col2", i)));
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "ConcatenatedField";
Solution 2
Try this..
DataTable dt = new DataTable();
foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["Col1"].ToString() + dr["Col2"].ToString());
}
Solution 3
DataTable dt = ds.Tables[0];
dt.Columns.Add("NewColumn", typeof(string));
foreach (DataRow dr in dt.Rows)
{
dr["NewColmun"] = dr["Column1"].ToString() + " " + dr["Co"].ToString();
}
Combo.DataSource = dt;
Combo.DisplayMember = "NewColumn";
Combo.ValueMember = "ValueField";
Comments
-
priyanka.sarkar almost 2 years
I have a datatable having 3 fields out of which I need to combine the values of the 2nd and 3rd field and display in the combo box. My approach is as under
DataTable dt = new DataTable(); dt.Columns.Add("Id", typeof(int)); dt.Columns.Add("Col1", typeof(string)); dt.Columns.Add("Col2", typeof(string)); Enumerable.Range(1, 10).ToList().ForEach(i => dt.Rows.Add(i, string.Concat("Col1", i), string.Concat("Col2", i))); comboBox1.DataSource = dt; comboBox1.DisplayMember = string.Format("{0} : {1}","Col1","Col2");
But I am getting the output as
System.Data.DataRowView
...Even I cannot change it from stored procedure level. I can however do this using entity approach by exposing some property but that will be a huge change at present. Is there any mechanism by which i can use the datatable as source and accomplish the work.
Thanks
-
Pundia almost 11 yearsI must add, the DataSource of the ComboBox SHOULD be set once you declared its DisplayMember and ValueMember. Otherwise, you can get data not displayed/obtained correctly (something as DataRow.etc).