BobSki
BobSki

Reputation: 1552

issue with adding an empty row in a databound combobox

I want to add an empty row in my combobox with no value. This is in case a user selects something from the combobox and then want to deselect it. Without an empty row this is required as I have already pointed out that I can do DELETE click and set the selected index to -1. User wants an empty row right at the top of the combobox. I'm loading my combobox like this....

sql="Select ID, Name from TblReference"

Dim da As New SqlDataAdapter(Sql, conn)
Dim ds As New DataSet

da.Fill(ds, "Dk")

'here I'm trying to add the extra row! This was previously supplied to me by @Plutonix. I am not able to get this to work.

Dim dr As DataRow = ds.Tables("Dk").NewRow
ds.Tables("Dk").Rows.InsertAt(dr, 0)

If ds.Tables("Dk").Rows.Count > 0 Then
    With c
      .DataSource = ds.Tables("Dk")
      .ValueMember = "ID"
      .DisplayMember = "Name"
      .SelectedIndex = -1
    End With
 End If

In this case C - is a combobox name that I pass to this function. I'm using the same function for multiple comboboxes which is why I need it.

ERROR says:

Unable to cast object of type 'System.Data.DataRow' to type 'SystemIconvertible'. Couldn't store system.data.datarow in ID column expected type is int32

Upvotes: 1

Views: 261

Answers (1)

A new row added to a DataTable has to conform to the data rules it read from the DB. In your case, it knows that Id has to be a valid Int32 but you did not supply any data for your row:

Dim dr = dtSample.NewRow
dr("Id") = -1
dr("Descr") = "(Blank)"
dtSample.Rows.InsertAt(dr, 0)

cboE.DataSource = dtSample
cboE.DisplayMember = "Descr"
cboE.ValueMember = "Id"

enter image description here


Another, perhaps better, way is the let SQL add the fake row. In MySQL, it would be:

SELECT  -1 As Id, '(Pick One)' As Descr UNION ALL SELECT Id, Descr FROM TABLE_NAME

Since Name is often a reserved word, Descr is used for illustration purposes.

Upvotes: 1

Related Questions