i am getting this error when i try to select an item from the drop-down box "Cannot have multiple items selected in a DropDownList". Can someone please help me i am not sure why i am getting this. here is my code:
private void Bind_GridView()
{
this.BindGroupNameList(DropDownList1);
}
private void GetGroupNameList(DropDownList DropDownList1)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
SqlConnection con2 = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd1 = new SqlCommand("select distinct Name" +
" from MyTable");
cmd1.Connection = con2;
con2.Open();
DropDownList1.DataSource = cmd1.ExecuteReader();
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Name";
DropDownList1.DataBind();
con2.Close();
DropDownList1.Items.FindByValue(ViewState["MyFilter"].ToString())
.Selected = true;
}
//on item change
protected void NameChanged(object sender, EventArgs e)
{
DropDownList DropDownList1 = (DropDownList)sender;
ViewState["MyFilter"] = DropDownList1.SelectedValue;
this.Bind_GridView();
}
and here is my dropdownbox in aspx
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="NameChanged"
DataTextField="Name" DataValueField="Name"
AppendDataBoundItems="true">
<asp:ListItem Text="ALL" Value="ALL"></asp:ListItem>
<asp:ListItem Text="Top 10" Value="10"></asp:ListItem>
</asp:DropDownList>
Here is the code for the page load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["MyFilter"] = "ALL";
this.Bind_GridView();
}
}
here is the method that calls GetGroupNameList:
private void Bind_GridView()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("sp_filter_Names");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@MyFilter", ViewState["MyFilter"].ToString());
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
GV_Test.DataSource = dt;
GV_Test.DataBind();
GetGroupNameList();
}
Change this line:
DropDownList1.Items.FindByValue(ViewState["MyFilter"].ToString())
.Selected = true;
to this:
DropDownList1.SelectedValue = ViewState["MyFilter"].ToString();
The problem is that you already have a selected item (probably the first in the list) and you are searching for another an have it selected as well. Keep in mind that having multiple selected items is valid for ListBox
and CheckListBox
, but not for a DropDownList
.
Making one of the ListItem
selected does not automatically unselect the other items in the ListItemColletion
.