Adding blank combo box item after using databind to populate the combo box.

Marilee

Newcomer
Joined
May 20, 2011
Location
South Africa
As an intern I was given a project to go through to try and understand the developer's code, and I've run into a problem:

I have two combo boxes that is populated from sql tables. The only problem is that if nothing is selected (which is possible), I get NullReferenceError: Object variable or With block variable not set.

I want to add an extra item to the combo box which says something like: "Please select", this will be displayed when no item is selected.

Here is some of the developers code:

Code:
        suburb.DataSource = DB.ReturnDataTable("Select ID,Suburb + ' - ' + City as Info1, Suburb as Info  from tblG2O_PostalInfo order by Suburb")
		suburb.DisplayMember = "Info"
        suburb.ValueMember = "ID"

That is where the suburb combo box is populated. ^^
(DB.ReturnTable is a custom method in a vb page, here is the code of that method:
Code:
    Public Function ReturnDataTable(ByVal sSQL As String) As DataTable
        Try
            Dim oConn As New OleDbConnection(DB_DSN)
            Dim retData As New DataTable
            Dim oRS As OleDbDataReader
            Dim oCmd As New OleDbCommand(sSQL, oConn)
            oConn.Open()
            oRS = oCmd.ExecuteReader()
            If oRS.HasRows = True Then
                retData.Load(oRS)
            End If
            oRS.Close()
            oRS = Nothing
            oConn.Close()
            Return retData
        Catch ex As Exception
            Trace("ReturnDataTable Error: " & sSQL & "<br>" & ex.Message)
            Return New DataTable
        End Try
    End Function
)
Code:
        Dim strsuburb As String = Trim(suburbc.SelectedItem("Info").ToString())

And that is where the selected suburb is assigned to a string. This string is used to update an existing table. This is the line where I'm having trouble.

I have tried:
Code:
        suburbc.Items.Insert(0, "*Please select*")
After the databind, but then I get a completely different error and if I do it before the databind, it's just overridden.
I've also tried using statements to check if the value returned is Null, but I studied in C# and Java, and am quite new to VB and the ways I've tried to do this haven't worked. My current employer prefers us all to work in VB.

Any solutions, tips or ideas will help.
Thank you. =)
 

orca44

Freshman
Joined
Dec 31, 2004
Location
Cape Town, South Africa
Do you get the NullReferenceException on this line?
Code:
 Dim strsuburb As String = Trim(suburbc.SelectedItem("Info").ToString())

Couldn't you test whether an item was selected on the combobox before assigning to the string or before you update the existing table?

If a value must be selected on the combobox before the data can be written back to the database, you could initially select the first item
in each combobox.
 
Top Bottom