使用C#不能在DropDownList中选择多个项目
发布时间:2020-12-15 20:00:44 所属栏目:百科 来源:网络整理
导读:当我尝试从下拉框“不能在DropDownList中选择多个项目”中选择项目时,我收到此错误.有人可以帮助我,我不知道为什么我得到这个.这是我的代码: private void Bind_GridView(){this.BindGroupNameList(DropDownList1);} private void GetGroupNameList(DropDow
当我尝试从下拉框“不能在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> 这是页面加载的代码: 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(); } 解决方法
改变这一行:
DropDownList1.Items.FindByValue(ViewState["MyFilter"].ToString()) .Selected = true; 对此: DropDownList1.SelectedValue = ViewState["MyFilter"].ToString(); 问题是你已经有了一个选定的项目(可能是列表中的第一个),而你正在搜索另一个项目也是如此.请记住,拥有多个选定项对ListBox和CheckListBox有效,但对DropDownList无效. 选择其中一个ListItem不会自动取消选择ListItemColletion中的其他项. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |