I have a combo box on a WinForms app in which an item may be selected, but it is not mandatory. I therefore need an \'Empty\' first item to indicate that no value has been s
I usually create an iterator for this type of thing. It avoids polluting your data, and works well with data-binding:
DataTable hierarchies = _database.GetAvailableHierarchies(cmbDataDefinition.SelectedValue.ToString()).Copy();//Calls SP
cmbHierarchies.DataSource = GetDisplayTable(hierarchies);
cmbHierarchies.ValueMember = "guid";
cmbHierarchies.DisplayMember = "ObjectLogicalName";
...
private IEnumerable GetDisplayTable(DataTable tbl)
{
yield return new { ObjectLogicalName = string.Empty, guid = Guid.Empty };
foreach (DataRow row in tbl.Rows)
yield return new { ObjectLogicalName = row["ObjectLogicalName"].ToString(), guid = (Guid)row["guid"] };
}
Disclaimer: I have not compiled this code, but have used this pattern many times.
Note: I have been in WPF and ASP.Net land for the last couple of years. Apparently the Winforms combo box wants an IList, not an IEnumerable. A more costly operation would be to create a list. This code is really stream-of-conciseness and I really, really have not compiled it:
DataTable hierarchies = _database.GetAvailableHierarchies(cmbDataDefinition.SelectedValue.ToString()).Copy();
List> list = new List>(hierarchies.Rows.Cast().Select(row => new KeyValuePair(row["Name"].ToString(), (Guid)row["Guid"])));
list.Insert(0, new KeyValuePair(string.Empty, Guid.Empty));
cmbHierarchies.DataSource = list;
cmbHierarchies.ValueMember = "Value";
cmbHierarchies.DisplayMember = "Key";