Skip to main content
 首页 » 编程设计

c#之你能在 asp C# 中填充一个预填充的下拉列表吗

2024年02月20日21mq0036

截至目前,我有一个 ddl,我已经用表中的信息填充了它。它是设置为自动回发的客户列表。我遇到的问题是,默认选择始终是列表中的第一个客户,当您单击其中的一个客户时,回发并获取所需的所有信息,并将选择设置为第一个客户并执行不做回帖。

所以我想到并一直在努力实现的一个修复方法是在 ddl 中放置一个空值,类似于“请选择客户”。 我已经进入 DDLs 编辑项目并添加了这个,但是对它不包含它的表的调用。有没有办法将其包含在内。

使用 Mozilla Firefox 时,我不会遇到这个问题,因为在回发之后它会停留在同一个客户身上。如果我能解决任何问题,我会尽力而为,如果有任何有用的代码,我可以提供

//save the value of the current selection to reselect later if still exists 
string origSelectedItem = ddlSelectedCustomer.SelectedValue; 
 
//clear and refill the list 
ddlSelectedCustomer.Items.Clear(); 
 
//check what role the user is in 
string usersRole = Roles.GetRolesForUser(Membership.GetUser().UserName)[0]; 
 
MembershipUser user = Membership.GetUser(); 
 
switch (usersRole) 
{ 
    case "SalesRep": 
         ddlSelectedCustomer.DataSource =  
         DAL.Util.getSalesRepCustomers((Guid)user.ProviderUserKey); 
         ddlSelectedCustomer.DataBind(); 
         break; 
 
    case "BasicUser": 
    case "Customer": 
         ddlSelectedCustomer.DataSource =  
         DAL.Util.getCustomersListForUser((Guid)user.ProviderUserKey); 
         ddlSelectedCustomer.DataBind(); 
         break; 
 
    case "Admin": 
    case "SuperAdmin": 
         ddlSelectedCustomer.DataSource = DAL.Util.getAllCustomersList();  
         ddlSelectedCustomer.DataBind(); 
         break; 
    default: 
         break; 
} 
 
//if user had a company selected, reselect it if it exists 
if (origSelectedItem != string.Empty) 
    ddlSelectedCustomer.SelectedValue = origSelectedItem; 
else if (ddlSelectedCustomer.Items.Count == 1)     
    //if only one item in the list, select it 
    ddlSelectedCustomer.Items[0].Selected = true; 

这也在网站母版页的代码隐藏中。

谢谢

请您参考如下方法:

您需要将 AppendDataBoundItems 设置为 true,然后您可以添加一个空的第一项。

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true"> 
    <asp:ListItem Text="" Value="" /> <!-- empty first item -->     
</asp:DropDownList> 

重要的是要注意,如果您多次绑定(bind)列表,您将需要清除列表,这样它就不会附加重复的项目。

如果你想在代码隐藏中添加空项目,在你清除列表之后,你可以这样做:

DropDownList1.Items.Clear(); 
DropDownList1.Items.Add(new ListItem(string.Empty, string.Empty)); 
 
//bind list