當我嘗試從下拉框「不能在DropDownList中選擇多個項目」中選擇項目時,出現此錯誤。有人可以幫助我,我不知道爲什麼我得到這個。這裏是我的代碼:使用C#不能在DropDownList中選擇多個項目
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();
}
,這裏是我的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>
這裏dropdownbox爲頁面加載代碼:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["MyFilter"] = "ALL";
this.Bind_GridView();
}
}
這裏是調用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();
}
在那裏在Page_Load中如果是則PL的任何代碼。張貼也是。 – Ratna
Ratina,我添加了頁面加載代碼。 thnx – moe
好吧,沒有問題在DropDownList1.Items.FindByValue(ViewState [「MyFilter」] .ToString())之前在GetGroupNameList(DropDownList DropDownList1)中添加一行, .Selected = true;插入這個 - > DropDownList1.selectedIndex = -1;添加了 – Ratna