Reputation: 223
I searched the site found several references to what I am looking to do. None worked in my case.
This seems like a simple problem. I am simply trying to set the default value to "--Select--".
I am filling the comboBox from a datatable from a database
Admin_BL admBL = new Admin_BL();
//populates datatable from database
dtBlds = admBL.GetActiveBuildings();
cmbBuilding.DataSource = dtBlds;
cmbBuilding.Text = "--Select--";
cmbBuilding.DisplayMember = "Building";
cmbBuilding.ValueMember = "Building";
I have used this also:
cmbBuilding.Items.Insert(0, "Select Bld");
This seems like a simple task I am not sure why this is not working in windows forms I would appreciate the help Thank You!
Upvotes: 0
Views: 1037
Reputation: 34152
considering "--Select--" is first item in your combobox, in runtime you select the first item by its index (of course it can be set in any other index like third item then index would be 2):
cmbBuilding.SelectedIndex = 0;
To add "--Select--" in function that populates the combobox items, before anything add "--Select--" to its items and then the items from database:
cmbBuilding.Items.Add("--Select--");
//add other items from db.
Upvotes: 0
Reputation: 1538
The issue here is that you're binding to an object and that object does not contain an entry for "-- Select --". Either you need to add this entry during the query:
SELECT 0 AS ID, '-- Select --' AS Building
UNION ALL
SELECT ID, BUILDING FROM <TABLE>
Then when you bind you'll find "-- Select --" is the first item.
If you don't want to change your query you can just insert a new row into the datatable once you've retrieved the data.
Assuming you've only got 2 columns in your datatable (ID and Building):
DataRow row = dtBlds.NewRow();
row[0] = 0;
row[1] = "-- Select --";
dtBlds.Rows.InsertAt(row, 0);
Once you've done this you can do the binding:
cmbBuilding.DataSource = dtBlds;
cmbBuilding.DisplayMember = "Building";
cmbBuilding.ValueMember = "Building";
Upvotes: 1