ListBox not showing correct selected value
Hi,
I have a pretty annoying problem with one of my pages listboxes. I want to take the text of the selected item in this particular multi select listbox and put the selected accounts in an arraylist. However when I submit the form, the selected index is correct sometimes and sometimes it comes to the first item even if I have something else selected. I read somewhere this could happen if I was binding it twice, but I am only binding it once, in an event handler of a Drop down control, I am not binding it in the page load and I tried using Listbox.SelectedIndex = -1 but it still does not work, oh and the EnableViewstate is also set to True for the Listbox. Its very frustrating as I cannot seem to find a way to get around it, could someone please tell me what I need to do to get my correct selected item in the listbox???
here is the code
// The event handler that populates the Listbox LbAccounts
protected void DDLSignatories_SelectedIndexChanged(object sender, EventArgs e)
{
GetAccounts();
}
protected void GetAccounts()
{
System.Data.SqlClient.SqlConnection cnn = new System.Data.SqlClient.SqlConnection(cnnString);
SqlCommand cmd = new SqlCommand("sp_GetEntityAcctstoRemoveSigs", cnn);
cmd.Parameters.AddWithValue("@EID", DDLEntities.SelectedValue);
cmd.Parameters.AddWithValue("@SigID", DDLSignatories.SelectedValue);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable Accounts = new DataTable();
da.Fill(Accounts);
if (Accounts.Rows.Count == 0)
{
Acct.Style["display"] = "none";
lblNoAccounts.Visible = true;
return;
}
lblNoAccounts.Visible = false;
Acct.Style["display"] = "block";
LbAccounts.DataSource = Accounts;
LbAccounts.DataTextField = "Name";
LbAccounts.DataValueField = "Type_ID";
LbAccounts.DataBind();
LbAccounts.SelectedIndex = -1;
}
// and Finally the Submit button
protected void BtnSubmit_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection cnn = new System.Data.SqlClient.SqlConnection(cnnString);
ArrayList accounts = new ArrayList();
foreach (ListItem li in LbAccounts.Items)
{
if (li.Selected == true)
{
accounts.Add(li);
}
}
}
The li.selected always returns the first item in the listbox?!? If someone can tellme of a way to get around this and get the correct selected accounts, It will be very much appreciated!! Thanx in advance!!
|