How to add an item to the top of a combobox? Thanks.
Hello,
I have a combobox which is populated using datatable:
Code:
Dim dt As New DataTable
dt = GetPatientList()
cbEPCDPatient.DataSource = dt
cbEPCDPatient.DisplayMember = "Patient"
cbEPCDPatient.ValueMember = "ID"
I want to add a new item manually as the first item in the combobox, here is what I added right after the above code:
Code:
cbEPCDPatient.Items.Add(New DictionaryEntry("Select Patient", 0))
It seems this item is NOT added to the combobox.
What is the right way to make this?
Thank you very much.
Re: How to add an item to the top of a combobox? Thanks.
You would use the Insert method rather than the Add method:
Code:
MyComboBox.Items.Insert(0, "First Item")
Edit - I just realized that your ComboBox is bound to a DataTable. If this is the case, then you would need to insert a row to your DataTable:
Code:
Dim r As DataRow = dt.NewRow()
r(0) = "Hello World!"
dt.Rows.InsertAt(r, 0)
Re: How to add an item to the top of a combobox? Thanks.
Thank you for your quick reply:
Code:
Dim dt As New DataTable
dt = GetPatientList()
cbEPCDPatient.DataSource = dt
cbEPCDPatient.DisplayMember = "Patient"
cbEPCDPatient.ValueMember = "ID"
'Dim r As DataRow = dt.NewRow()
'r(0) = "Select Patient"
'dt.Rows.InsertAt(r, 0)
cbEPCDPatient.Items.Add(New DictionaryEntry("Select Patient", 0))
After added the code, the combobox shows no item at all, how do I fix it?
Re: How to add an item to the top of a combobox? Thanks.
After debugging, I believe the issue rests here:
r(0) = "Select Patient"
Re: How to add an item to the top of a combobox? Thanks.
You've got it in the wrong order, do this instead;
Code:
Dim dt As New DataTable
dt = GetPatientList()
Dim r As DataRow = dt.NewRow()
r(0) = "Select Patient"
dt.Rows.InsertAt(r, 0)
cbEPCDPatient.DataSource = dt
cbEPCDPatient.DisplayMember = "Patient"
cbEPCDPatient.ValueMember = "ID"
Re: How to add an item to the top of a combobox? Thanks.
Fixed. Thank you.
Code:
Dim dt As New DataTable
dt = GetPatientList()
Dim r As DataRow = dt.NewRow()
Try
r("ID") = 0
r("Patient") = "Select Patient"
Catch ex As Exception
Throw ex
End Try
dt.Rows.InsertAt(r, 0)
cbEPCDPatient.DataSource = dt
cbEPCDPatient.DisplayMember = "Patient"
cbEPCDPatient.ValueMember = "ID"