BobSki
BobSki

Reputation: 1552

Adding an empty row to databound combobox Vb.net

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...

    dt.Load(cmd.ExecuteReader)

    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.

EDIT

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

Upvotes: 1

Views: 2942

Answers (2)

Shin
Shin

Reputation: 1

Try this one, I already try to use it and it works. :)

Combobox1.datasource = table
Combobox1.SelectedIndex = -1
ComboBox1.DisplayMember = "Column you want to display"
ComboBox1.ValueMember = "ID"

Upvotes: 0

Bugs
Bugs

Reputation: 4489

I add a union in my procedure with blank values:

SELECT ID = 0,
       Name = ''

UNION

SELECT ID,
       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") = ""
dt.Rows.Add(dr)

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"

Or as Plutonix has said in a comment:

dt.Rows.InsertAt(dr,0)

Upvotes: 2

Related Questions