How to prevent a combobox first item from being selected on DataSet.Merge()
I've got a ComboBox which items are coming from a DataTable in a DataSet. When there is no item selected (comb开发者_如何学Co.selectedindex = -1) and I do a .Merge() on the DataSet the first element of the combobox is selected. When there is an item already selected, the item stay selected.
How can I prevent this and make it so that even if I do a MyDataSet.Merge(otherDs) the selectedIndex remains at -1 (no selection)?
A combo box is really designed to avoid having no selection. As you've seen it is possible to get it in that state by setting SelectedIndex to -1, but that's not really the metaphor the ComboBox designers were going for. The idea is that the user is restricted to the combo box values. So if "Nothing Selected" is a valid value for the box (or at least valid for the initial load) it needs to be part of your data table. It's common to have a row with ValueMember column as DBNull.Value and the DisplayMember as "Nothing Selected" or "Please select a value" or whatever.
Then your UI validation can ensure they didn't leave it on that value.
UPDATE: You can always add the value last minute if you can't add the value from the data source procedure. In fact, some might consider this a good idea since this "nothing selected" option is purely a UI state.
DataRow nullRow = MyDataSet.MyTable.NewRow();
nullRow["VAL_COLUMN"] = DBNull.Value;
nullRow["DISP_COLUMN"] = "Please select a value...";
MyDataSet.MyTable.Rows.Insert(0, nullRow); //might have those parameters backwards..
精彩评论