简体   繁体   中英

Dropdown default select value

This is a Dropdown control where I am binding the data, after bind I am putting the select statement. Even though the index is kept to 0 always select comes last like this:

Current output:

india
Auz
US
--select--

Required output:

--select--
india
AUZ
US

My Code

ddlcounty.DataSource = dtNew;
ddlcounty.DataTextField = "Weight";
ddlcounty.DataValueField = "Weight";
ddlcounty.DataBind();

ddlcounty.Items.Add("--Select--");
ddlcounty.SelectedValue = "0";

What is the change required here?

Thanks

You're doing your binding first.

When you get to the part where you are adding your default condition, you're actually adding to the end of the list.

Instead of :-

ddlcounty.Items.Add("--Select--");

Do :-

ddlcounty.Items.Insert(0, new ListItem("--Select--"));

This will insert your default option as the first element of Items .

Announced edit

You won't need :-

ddlcounty.SelectedValue = 0;

.. as if you don't explicitly specify, the first item in a drop down list is automatically selected.

If, however, you want to be explicit about it, you can do the following:-

ddlcounty.Items.Insert(0, new ListItem("--Select--","0"));
ddlcounty.SelectedValue = 0;

Would you please try below way:

Just set AppendDataBoundItems to true and Insert a ListItem as selected, and 'ClearSelection' before selecting item as below.

ddlcounty.AppendDataBoundItems = true;
ddlcounty.DataSource = dtNew;
ddlcounty.DataTextField = "Weight";
ddlcounty.DataValueField = "Weight";
ddlcounty.DataBind();

ddlcounty.ClearSelection();
ddlcounty.Items.Insert(0, new ListItem { Value = "0", Text = "--Select--", Selected = true });
ddlcounty.SelectedValue = "0";

You could also declare the "select one" ListItem declaratively in your aspx page like so

 <asp:DropDownList ID="ddUIC" runat="server" AppendDataBoundItems="true" Width="200px" BackColor="White" Font-Size="10px" SelectedValue='<%# Bind("Weight") %>' DataTextField="Weight" DataValueField="Weight" >
     <asp:ListItem Text="Select One" Value=""></asp:ListItem>
 /asp:DropDownList>

But your AppendDataBoundItems would have to be set to true

And you could still perform your databinding on the backend.

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