简体   繁体   中英

ASP Dropdown on Page_Load

I want to create a Drop Down using Aspx, which will list all the items contained in a data source but it will have an additional default value of "selected".

In the aspx file, I have:

<aspx:DropDownList
    ID="ddl1"
    runat="server"/>

In my aspx.cs file, I have a page_load, which contains:

protected void Page_Load(object sender, EventArgs e)
{
  ddl1.DataSource = LocationofData;
  ddl1.DataBind();
}

And let's assume that LocationofData will populate the values "a,b,c,etc...". I want the default value to be "--selected--"

How should I approach this?

Thanks

You can add this code

ddl1.Items.Add("--selected--"); //After your bind

So :

ddl1.DataSource = LocationofData;
ddl1.DataBind();
ddl1.Items.Add("--selected--"); //After your bind

Link : http://msdn.microsoft.com/en-us/library/e7s6873c.aspx

You can also use Insert method

Link : http://msdn.microsoft.com/en-us/library/ffx2x2y2.aspx

Try this

protected void Page_Load(object sender, EventArgs e)
{
   if(!Page.IsPostBack)
   {
      ddl1.DataSource = LocationofData;
      ddl1.DataBind();

      //first item in the list
      ddl1.Items.Insert(0, new ListItem("-- Select--",""));
   }
}

I think best practice is to use ondatabound which calls the BaseDataBoundControl.DataBound event: ASP.NET Control:

<asp:DropDownList runat="server" ID="ddl1"
  ondatabound="MyListDataBound"></asp:DropDownList>

Code behind:

protected void MyListDataBound(object sender, EventArgs e)
{
    ddl1.Items.Insert(0, new ListItem("- Select -", ""));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM