I know this is probably a basic question, but I'm stuck and can't seem to figure it out :-/

This is in VB.NET 2005 and I'm making a windows forms app. I'm filling a DataTable from a SQL command, and then binding a dropdownlist to that DataTable. I'm assigning the DisplayMember and ValueMember just fine, and the dropdownlist is working fine. But what I want to do is after binding it, add a "blank" choice (or some other text like "please choose something" to the first slot, and default to that being selected when the app runs. I know it's simple, I'm just blanking out here. Thanks!

Here's the code for what I'm doing:

Private Sub BindAccounts()
        Dim conn As New SqlConnection()
        Dim myCommand As New SqlCommand
        Dim da As New SqlDataAdapter
        Dim myData As New DataTable

        Dim SQL As String
        Dim sSQL As String

        SQL = "server=" & My.Settings.DataSource & ";" _
         & "user id=" & Login.txtUserName.Text & ";" _
         & "password=" & Login.txtPassword.Text & ";" _
         & "database=" & My.Settings.InitialCatalog

        conn.ConnectionString = SQL
        sSQL = "select distinct lngAccountID_pk, strAccountName"
        sSQL = sSQL & " from tblAccounts"
        sSQL = sSQL & " where lngAccountID_pk in (select accountid from tblstaging)"
        sSQL = sSQL & " order by strAccountName"


                myCommand.Connection = conn
                myCommand.CommandText = sSQL
                myCommand.CommandType = CommandType.Text

                da.SelectCommand = myCommand

                ddlAccount.DataSource = myData
                ddlAccount.DisplayMember = "strAccountName"
                ddlAccount.ValueMember = "lngAccountID_pk"

            Catch myerror As SqlException
                MsgBox("There was an error reading from the database: " 
& myerror.Message)

            End Try

            ddlAccount.SelectedIndex = 0


        Catch myerror As SqlException
            MessageBox.Show("Error Connecting to Database: " &
        End Try
    End Sub

Derrrr, I found some old C# code I used in another project, I'm hoping to try it tonight after work. I think this might work?

// Add blank option
ddlDepartment.Items.Insert(0, new ListItem("", ""));

I think my problem was in the ListItem part - I'd forgotten about that.

On a related note (or maybe not), when I bind the account list it is firing the selection changed event and then trying to bind the datagrid (when I load the form), and is crapping out on that. Basically it's trying to do the SQL query before there is data for it, I think. Is there anything like a PostBack in forms programming? I don't want it to bind the datagrid on load....ah well, I'll figure it out!

This article has been dead for over six months. Start a new discussion instead.