开发者

how to use select type in Dropdownlist in C# without declaring as a list item

I guess this is simple, but i couldnot figure it out.

i have a开发者_如何转开发 dropdown list with values

America
Asia
Europe

I need to the display the ddl as Select Type and when i click the dropdownlist to see the values in it, it should display the three values, but i should not use Select Type as a list item and it should not be displayed in the list. It should only be used as a default text in ddl.

Thanks,


Windows Forms?

If you populate your combobox like this:

        this.comboBox1.Items.Add("Select...");
        this.comboBox1.Items.Add("America");
        this.comboBox1.Items.Add("Asia");
        this.comboBox1.Items.Add("Yurrup");

Then, attach a DropDown event, to remove the first option on first drop down.

    private void comboBox1_DropDown(object sender, EventArgs e)
    {
        if (comboBox1.Items[0].ToString() == "Select...")
        {
            comboBox1.Items.RemoveAt(0);
        }
    }


<asp:DropDownList runat="server">
    <ListItem Text="Select Type" Value="0" />
    <ListItem Text="America" Value="1" />
    <ListItem Text="Asia" Value="2" />
    <ListItem Text="Europe" Value="3" />
</asp:DropDownList>

Then I would add an "onclick" event to the <asp:DropDownList> like so:

<asp:DropDownList runat="server" onclick="javascript:RemoveDefault(this);">

and have a javascript function RemoveDefault() that did the following:

function RemoveDefault(select) { if (select.options[0].value == "0") select.remove(0); }


I would add the ListItem to the list with its text set to "Select Type" and its value set to an empty string. In the code behind when you're handling the list, you would programmatically handle the possibility of an empty string selected value.

So given

ddl.Items.Add(new ListItem("Select Type", string.Empty));
ddl.Items.Add(new ListItem("America", "America"));
ddl.Items.Add(new ListItem("Asia", "Asia"));
ddl.Items.Add(new ListItem("Europe", "Europe"));

You'd handle it like

if (ddl.SelectedValue != string.Empty)
{
    // do what you need to do
}
else
{
    // OK to ignore? re-prompt user? etc.
}


You have to create a new item, make sure it's at first position in the list, and then programmatically ignore it when the user selects it.

Or as Cheeso suggests remove the first "fake" item on first drop-down.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜