简体   繁体   English

下拉菜单默认选择值

[英]Dropdown default select value

This is a Dropdown control where I am binding the data, after bind I am putting the select statement. 这是一个下拉控件,用于绑定数据,在绑定之后,我将放置select语句。 Even though the index is kept to 0 always select comes last like this: 即使索引保持为0,总会这样选择最后一个:

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 . 这会将您的默认选项作为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. 只需将AppendDataBoundItems设置为true并在选定项之前插入ListItem为选定项,然后插入“ ClearSelection”,如下所示。

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 您还可以在aspx页面中声明性地声明“选择一个” ListItem,如下所示

 <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 但是您的AppendDataBoundItems必须设置为true

And you could still perform your databinding on the backend. 而且您仍然可以在后端执行数据绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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