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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…