asp.net cannot select multiple cause analyses and solutions in DropDownList

  • 2020-05-17 05:16:08
  • OfStack

Sample code:
 
BulkStockBll bll = new BulkStockBll(); 
DataSet ds = bll.GetBulkStock(); 
this.ddl_BulkStock.DataTextField = "Name" ; 
this.ddl_BulkStock.DataValueField = "ID" ; 
this.ddl_BulkStock.DataSource = ds; 
this.ddl_BulkStock.DataBind(); 
this.ddl_BulkStock.Items.Add(new ListItem( " all ", "0" ));// The first 1 Time to choose!  
this.ddl_BulkStock.Items.FindByValue("0" ).Selected = true; 
******************************* 
this.ddl_BulkStock.Items.FindByValue(infobulkstockid).Selected = true;// The first 2 Time to choose!  
****************************** 

There are two choices, so error.
When page load, Selected of index0 = true, you choose another Selected of index1 and true, you will report an error.
dropDownList. Items[x].Selected = true/false; dropDownList. SelectedIndex = x.
There are two solutions:
(1) when selecting an option, use the following code instead of the above green code
this .ddl_BulkStock.SelectedIndex = ddl_BulkStock.Items.IndexOf(ddl_BulkStock.Items.FindByValue(infobulkstockid));
(2) before selecting an option each time, use the ClearSelection operation.
this.ddl_BulkStock.ClearSelection();


Today on the edit page: you cannot select multiple items in DropDownList.

I found out the reason carefully:
 
<asp:DropDownList ID="Com_Ygrenshu" runat="server" style="margin-left:8px;"> 
<asp:ListItem Value="0"> Please select number </asp:ListItem> 
<asp:ListItem Selected="True" Value="5">5 People here </asp:ListItem> 
<asp:ListItem Value="10">5-10  people </asp:ListItem> 
<asp:ListItem Value="50">11-50  people </asp:ListItem> 
</asp:DropDownList> 

I re-bound the code of the data in the edit page:
 
for (int i = 0; i < this.Com_Ygrenshu.Items.Count; i++) 
{ 
Com_Ygrenshu.Items[i].Selected = false; 

// If you didn't have this up here 1 Then there will be mistakes : Not in the  DropDownList  Select multiple items from  
if (Com_Ygrenshu.Items[i].Value.Trim() == ds.Tables[0].Rows[0]["Empl_Num"].ToString().Trim()) 
{ 
Com_Ygrenshu.Items[i].Selected = true; 
} 
} 

The reason is: your DropDownList has two options Selected="True", so error!
# dropdownlist controls

Related articles: