Bobski Bobski - 1 year ago 76 Question

Adding an empty row to databound combobox

I know this question has been asked a thousand times, I have done my research but I am unable to find anything that actually fixes this issue for me. I am loading a combobox from a datatable, and setting the .selectedindex=-1 so that the user can make a selection. But if user changes their mind and wants to unselect it, they cannot do that, since all items in the drop down have a value. I came across a few where it is suggested that users click delete and which would set the .selectedIndex = -1 but I'd rather somehow add an empty value in the drop down that can be selected. here's what my code looks like...

I run a stored procedure and load it into DataTable which is used as my datasource...


oCombobox.DataSource = dt
oCombobox.ValueMember = "ID"
oCombobox.DisplayMember = "Name"
oCombobox.SelectedIndex = -1

I have done quite a bit of research and simply can't find a workable solution for VB.Net, I've come across a few solution to C# however DataTable.AddRow() is not one of the functions for VB therefore am unable to implement it in my project.


Dim dr As DataRow = dt.NewRow
dr("ID") = 0
dr("Name") = ""

Answer Source

I add a union in my procedure with blank values:

       Name = ''


FROM YourTable

You can then do an Order By so that 0 starts at the top. Not sure if this is the best way of doing it but it's worked for me in the past.

You could modify the DataTable and add a new row with blank values:

Dim dr As DataRow = dt.NewRow
dr("ID") = 0
dr("Name") = ""

If you want to order the DataTable your best bet will be to use a DataView:

Dim dv As New DataView(dt)
dv.Sort = "ID ASC"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download