Add an empty option

MTmace

Member
Joined
Feb 1, 2005
Messages
9
Programming Experience
Beginner
I have a combo box bound to datatable. How would i add a record with no entry in it?

MTmace
 
Hey MTmace,

You have three options here as far as i can see.

1) If you are binding the combobox at design time and don't want to bind it programmatically you'll have to add a blank record into the database (which is not the best idea in the world).

2) You could populate the comboBox manually completely ignoring databinding. and add a blank record at the start.

3) You could bind the combobox at runtime using something similar to the following code in the load event of your form.

VB.NET:
MyComboBox.DataSource = MyDataTable
MyComboBox.DataTextField = "Name"
MyComboBox.DataValueField = "ID"
MyComboBox.DataBind()
MyComboBox.Items.Insert(0,"Leave this blank or put what you want in")
MyComboBox.Items.FindByText("").Selected = True

Hope this helps.
 
Thanks

I am using the runtime option.
I did get an error:
the findbytext is not a member of the system.windows.forms.combobox.objectcollection

Is there another class that I need to add that includes the findbytext?

Thanks,

MTmace
 
Use a variation of option #1 above: I make the SELECT statement put it in.

-tg
 
IMHO - If you have a local datatable; I would modify that with a blank record rather than your DB. That's assuming you're adament about using data binding. I've pretty much sold my soul to "while sqlRead.Read"s. :eek:
 
Generally speaking it makes no sense to add an extra blank entry. Do you actually want the user to select a blank value, or do you actually want them to select no value? If it's the latter, here's what I do:
VB.NET:
    Private Sub ComboBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles ComboBox1.KeyDown
        If e.KeyCode = Keys.Delete Then
            Me.ComboBox1.SelectedIndex = -1
        End If
    End Sub
Then the user can use the Delete key (or some other key if you prefer) to clear the selection. If your ComboBox is data-bound you may have to set the SelectedIndex to -1 twice to make it work.
 
hi
If u want to use databinding, then u may change ur select statement like that "select Column1 from table1 union select '' as column1" and fill the dataset using this, now ur combo box always has the empty value as a first record.
 
Back
Top