Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

c# - How to add dropdown list default value

I am using asp.net for fetching data from sql table to dropdown list. The problem is that, when I give default selection to the dropdown list. It does not take the default value. Please see the code

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand("select * from States_agri", conn);
        SqlDataReader dr = cmd.ExecuteReader();
        ddl_state.DataSource = dr;
        ddl_state.Items.Clear();
        ddl_state.Items.Add("--Please Select state--");
        ddl_state.DataTextField = "StateName";
        ddl_state.DataValueField = "StateID";
        ddl_state.DataBind();
        conn.Close();
    }
}
`

Also Please see the dropdown list aspx code for your reference.

<asp:UpdatePanel ID="FormUpdate" runat="server" UpdateMode="Conditional">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="ddl_state" EventName="SelectedIndexChanged" />
    </Triggers>
    <ContentTemplate>
        <table>
            <tr>
                 <td>State*</td>
                 <td>
                     <asp:DropDownList ID="ddl_state" runat="server" CssClass="cbfld-popup1" AutoPostBack="true" OnSelectedIndexChanged="ddl_state_SelectedIndexChanged">
                     <asp:ListItem Enabled="true" Selected="True" Text="Please select State"></asp:ListItem>
                     </asp:DropDownList>
                 </td>

            </tr>
            <tr>
                 <td>District*</td>
                 <td>
                     <asp:DropDownList ID="ddl_district" CssClass="cbfld-popup1" runat="server">
                     <asp:ListItem Enabled="true" Selected="True" Text="Please select city"></asp:ListItem>
                                                                                                      </td>
            </tr>
         </table>
     </ContentTemplate>
</asp:UpdatePanel>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After data-binding, do this:

ddl_state.Items.Insert(0, new ListItem("Select","NA")

Or add it in markup as:

<asp:DropDownList .. AppendDataBoundItems="true">
   <Items>
       <asp:ListItem Text="Select" Value="" />
   </Items>
</asp:DropDownList>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...