如何为此ASP.NET DropDownList控件添加默认的“选择”选项?

我是一名新的ASP.NET开发人员,我正在尝试学习Linq-To-Entities。 我试图将DropDownList绑定到Linq语句,以检索状态实体中的状态列表。 一切都很好。 但是,我现在正在尝试向DropDownList添加“选择”选项,但它不适用于我。 你能告诉我怎么解决这个问题吗?

ASP.NET代码:

 

代码隐藏:

 protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DropDownList1.Items.Add(new ListItem("Select", "0", true)); bindStatusDropDownList(); } } private void bindStatusDropDownList() { Status status = new Status(); DropDownList1.DataSource = status.getData(); DropDownList1.DataValueField = "ID"; DropDownList1.DataTextField = "Description"; DropDownList1.DataBind(); } 

更新:

我也尝试在DropDownList的标记集中做,但它对我来说也不起作用

    

它无法工作的原因是因为您正在向列表中添加项目,然后使用新的DataSource覆盖整个列表,这将清除并重新填充列表,从而丢失第一个手动添加的项目。

所以,你需要反向执行此操作:

 Status status = new Status(); DropDownList1.DataSource = status.getData(); DropDownList1.DataValueField = "ID"; DropDownList1.DataTextField = "Description"; DropDownList1.DataBind(); // Then add your first item DropDownList1.Items.Insert(0, "Select"); 

虽然这是一个相当古老的问题,但另一种方法是更改AppendDataBoundItems属性。 所以代码将是:

    

我试过以下代码。 它对我很好

 ManageOrder Order = new ManageOrder(); Organization.DataSource = Order.getAllOrganization(Session["userID"].ToString()); Organization.DataValueField = "OrganisationID"; Organization.DataTextField = "OrganisationName"; Organization.DataBind(); Organization.Items.Insert(0, new ListItem("Select Organisation", "0")); 

移动DropDownList1.Items.Add(new ListItem(“Select”,“0”,true)); 在bindStatusDropDownList()之后;

所以:

  if (!IsPostBack) { bindStatusDropDownList(); //first create structure DropDownList1.Items.Add(new ListItem("Select", "0", true)); // after add item } 

如果您执行“添加”,它会将其添加到列表的底部。 如果您希望将项目添加到列表顶部,则需要执行“插入”。

 Private Sub YourWebPage_PreRenderComplete(sender As Object, e As EventArgs) Handles Me.PreRenderComplete If Not IsPostBack Then DropDownList1.Items.Insert(0, "Select") End If End Sub