简体   繁体   中英

How to include selected value in populated drop-down list

I am using linq to fetch from database to populate in drop down list in asp.net using below code:

XXXDataContext summary = new XXXDataContext();
protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
      var binmy = ( from bin in summary SUBPRODUCTs
                    order by bin.SUBID
                    select new { bin.SUBID, bin.SUBValue }
                  );                      
      dropdownsummary.DataValueField = "SUBID";
      dropdownsummary.DataTextField = "SUBValue";
      dropdownsummary.DataSource = binmy;
      DataBind();
   }
}

Here I want to include 'All' as default value how to do that?

Add this item in the html dropdown declaration and set the 'AppendDataBoundItems' property to true. See below...

<asp:DropDownList ID="dropdownsummary" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Selected="True" Value="-1" Text="All"></asp:ListItem>
</asp:DropDownList>

Use:

dropdownsummary.DataBind();  

Instead of :

DataBind();  

Try This

dropdownsummary.DataValueField = "SUBID";
dropdownsummary.DataTextField = "SUBValue";
dropdownsummary.DataSource = binmy;
dropdownsummary.Items.Insert("0", new ListItem ( "All" , "0" ));

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