3

The above error occurs on a SelectedIndexChanged click event on a listbox.

in debug the value returned is "", however when you look at the webpage source code there are definitely values.

Here's my listbox:

<asp:ListBox ID="lstBxMyList" runat="server" CssClass="binorderlst1"
     DataTextField="myName" 
     DataValueField="myID" 
     OnSelectedIndexChanged ="lstBxMyList_SelectedIndexChanged"
     AutoPostBack="true" Rows="10">
</asp:ListBox>

Here's the event:

protected void lstBxMyList_SelectedIndexChanged(object sender, EventArgs e)
{
    myID = Convert.ToInt32(lstBxSiteList.SelectedValue.ToString());

    ... rest of code
}

For completeness here's the data binding:

private void BindLstBxMyList(int myOtherID)
    {
        DataTable dt = new DataTable();
        SqlConnection conn;
        SqlCommand comm;

        using (conn = new SqlConnection(aSHconns.aconn))
        {
            comm = new SqlCommand("myStoredProc", conn);
            comm.CommandType = CommandType.StoredProcedure;
            comm.Parameters.Add(new SqlParameter("@myOtherID", SqlDbType.Int));
            comm.Parameters["@myOtherID"].Value = myOtherID;
            SqlDataAdapter sqlDa = new SqlDataAdapter(comm);

            try
            {
                conn.Open();
                 sqlDa.Fill(dt);
                 if (dt.Rows.Count > 0)
                 {
                     lstBxMyList.DataSource = dt;
                     lstBxMyList.DataTextField = "myName";
                     lstBxMyList.DataValueField = "myID";
                     lstBxMyList.DataBind();
                 }

            }

            finally 
            {
                conn.Close();
            }
        }

    }

If I revert back to a SqlDataSource the listbox returns values. Bt I need to repopulate the list, so I need the code behind databind (unless there is a better way of course)

So why is the listbox selected value returning an empty string? Any help would be gratefully received.

ComfortablyNumb
  • 1,448
  • 10
  • 37
  • 64

1 Answers1

6

You have property AutoPostBack = "True" this will make a postback on each selected index changed. So, before it goes to Selected index changed event it has to hit Page load where you are binding your listbox. So, when it hits page load, the selected index will be changed to default item. So, try the following code.

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
             //Bind your listbox here
            }
         }
Praveen Mitta
  • 1,408
  • 2
  • 27
  • 48