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();
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.
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.
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.
<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>
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With