开发者

Autoselecting the only option in a dropdownlist

I developed a Dropdownlist called dropdownlist3 which has only one item in the Dropdownlist, so I want that only option to be automatically selected. How can I do this?

My code is as foll开发者_如何转开发ows

protected void Page_Load(object sender, EventArgs e)
{
        if (DropDownList3.Items.Count.Equals(1))
        {
            DropDownList3.Text = DropDownList3.Items[0].ToString();
        }
}

I tried the following code:

if (DropDownList3.Items.Count == 1)
    DropDownList3.SelectedIndex = 0;  

However this didn't work.


Normally a drop down list always has an item selected, by default this will be the first item in the list.

If your drop down only has one item in the list, then this will be selected by default. You can try this on a simple .aspx page:

<asp:DropDownList ID="DropDownList1" runat="server">
    <asp:ListItem>Test</asp:ListItem>
</asp:DropDownList>

What this looks like for me:

Autoselecting the only option in a dropdownlist

This is a feature of the underlying html "select" control rather than the ASP.Net DropDownList class.

Of course this relies on DropDownList3 being a System.Web.UI.WebControls.DropDownList instance (i.e. actually using a select control under the covers) and there not being any JavaScript that is customising the drop down in "extreme" ways (like dynamically replacing the select control with a text box and some divs). If this isn't the case then you will need to supply more detail.


You can use SelectedValue:

DropDownList3.SelectedValue = DropDownList3.Items[0].Value;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜