How to set the first index as empty in combobox

I have a combobox connected to a data source. In this combo box, I have to add an empty field with index 0.

I wrote the following code to get the entries.

public List<TBASubType> GetSubType(int typ) { using (var tr = session.BeginTransaction()) { try { List<TBASubType> lstSubTypes = (from sbt in session.Query<TBASubType>() where sbt.FType == typ select sbt).ToList(); tr.Commit(); return lstSubTypes; } catch (Exception ex) { CusException cex = new CusException(ex); cex.Write(); return null; } } } 

After that, it contacts the combobox with the data binding source, as shown below.

 M3.CM.BAL.CM CMobj = new M3.CM.BAL.CM(wSession.CreateSession()); lstSubTypes = CMobj.GetSubType(type); this.tBASubTypeBindingSource.DataSource = lstSubTypes; 
+7
c # winforms nhibernate
source share
2 answers

If you just want to choose nothing initially, you can use

 comboBox1.SelectedIndex=-1; 
+19
source share

Thus, you cannot change Elements when you are bound to a DataSource, then only the option to add an empty string changes your data source. Create an empty object and add it to the data source. For example. if you have a list of some Person entities bound to combobox:

 var people = Builder<Person>.CreateListOfSize(10).Build().ToList(); people.Insert(0, new Person { Name = "" }); comboBox1.DisplayMember = "Name"; comboBox1.DataSource = people; 

You can define the static property Empty in your class:

 public static readonly Person Empty = new Person { Name = "" }; 

And use it to insert an empty default element:

 people.Insert(0, Person.Empty); 

This will also check if the selected item is the default:

 private void comboBox_SelectedIndexChanged(object sender, EventArgs e) { Person person = (Person)comboBox.SelectedItem; if (person == Person.Empty) MessageBox.Show("Default item selected!"); } 
+9
source share

All Articles