Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drop down list value in asp.net

I want to add a value to the drop down list that cannot be selected, like a title. Ex: I have a month drop down list. The very first item should be "select month" this should not be selected. And next is from January to december. How can I do that?

And this is my current code.

string selectmonth = "select * from tblmonth";
SqlCommand scmselect = new SqlCommand(selectmonth, scnbuboy);

SqlDataReader sdrselect = scmselect.ExecuteReader();

drmonth.DataTextField = "month";
drmonth.DataValueField = "monthID";
drmonth.DataSource = sdrselect;

drmonth.DataBind();
like image 509
wormwood Avatar asked Aug 21 '13 10:08

wormwood


People also ask

Which property is used for adding values in dropdown list?

After dragging, our web form looks like the below. Now, to add items to the list, visual studio provides Items property where we can add items. The property window looks like this.

How can show the selected value of DropDownList in ASP NET MVC?

The DropDownList is generated using the Html. DropDownListFor Html Helper method. The first parameter is the Lambda expression for specifying the property that will hold the Selected Value of the DropDownList when the Form is submitted.

How can I select multiple options from a drop-down list in asp net?

The ASP.NET Core MultiSelect Dropdown is a quick replacement for the HTML select tag for selecting multiple values. HTML MultiSelect Dropdown is a textbox control that allows the user to type or select multiple values from a list of predefined options.


2 Answers

<asp:DropDownList ID="DdlMonths" runat="server">
    <asp:ListItem Enabled="true" Text="Select Month" Value="-1"></asp:ListItem>
    <asp:ListItem Text="January" Value="1"></asp:ListItem>
    <asp:ListItem Text="February" Value="2"></asp:ListItem>
    ....
    <asp:ListItem Text="December" Value="12"></asp:ListItem>
</asp:DropDownList>

You can even use a RequiredFieldValidator which ignore this item, it considers it as unselected.

<asp:RequiredFieldValidator ID="ReqMonth" runat="server" ControlToValidate="DdlMonths"
    InitialValue="-1">
</asp:RequiredFieldValidator>
like image 64
Tim Schmelter Avatar answered Oct 21 '22 08:10

Tim Schmelter


You can add an empty value such as:

ddlmonths.Items.Insert(0, new ListItem("Select Month", ""))

And just add a validation to prevent chosing empty option such as asp:RequiredFieldValidator.

like image 43
7alhashmi Avatar answered Oct 21 '22 09:10

7alhashmi