views:

306

answers:

4

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,

+2  A: 

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);
        }
    }
Cheeso
I'm guessing you wrote this before it was properly tagged
hunter
This is still helpful!!
superstar
yes I did - saw the referral to the other Q after I posted this.
Cheeso
But now I see that the questioner has specified ASP.NET. So, this answer is irrelevant!
Cheeso
A: 

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.

Anna Lear
+1  A: 
<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); }
hunter
do you have an onclick event for a dropdown list?
superstar
@superstar, that would be a javascript event in this case. A safer approach would be to add the "onclick" attribute in code behind. Something like `ddl.Attributes.Add("onclick", "javascript:RemoveDefault(this)");` This also assumes someone actually *clicks* on the list.
Anthony Pegram
A: 

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.
}
Anthony Pegram