drop down list value in asp.net

前端 未结 9 1911
刺人心
刺人心 2021-01-18 08:29

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

相关标签:
9条回答
  • 2021-01-18 08:29

    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.

    0 讨论(0)
  • 2021-01-18 08:30

    Say you have a drop down called ddlMonths:

    ddlMonths.Items.Insert(0,new ListItem("Select a month","-1");
    
    0 讨论(0)
  • 2021-01-18 08:32

    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>
    
    0 讨论(0)
  • 2021-01-18 08:43
    <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>
    
    0 讨论(0)
  • 2021-01-18 08:44

    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();
    }
    
    0 讨论(0)
  • 2021-01-18 08:46

    You can try this

    your_ddl_id.Items.Insert(0,new ListItem("Select","");
    
    0 讨论(0)
提交回复
热议问题