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 sho
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
.
Say you have a drop down called ddlMonths
:
ddlMonths.Items.Insert(0,new ListItem("Select a month","-1");
In simple way, Its not possible. Because DropdownList
contain ListItem
and it will be selected by default
But, you can use ValidationControl
for that:
<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic"
ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>
<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>
To add items to drop down list with value in asp.net using c# just add below codes for example:
try
{
SqlConnection conn = new SqlConnection(conStr);
SqlCommand comm = conn.CreateCommand();
comm = conn.CreateCommand();
comm.CommandText = "SELECT title,gid from Groups";
comm.CommandType = CommandType.Text;
conn.Open();
SqlDataReader dr = comm.ExecuteReader();
while (dr.Read())
{
dropDownList.Items.Add(new
ListItem(dr[0].ToString(),dr[1].ToString()));
}
}
catch (Exception e)
{
lblText.Text = e.Message;
}
finally
{
conn.Close();
}
You can try this
your_ddl_id.Items.Insert(0,new ListItem("Select","");