i m using following code to populate dropdownlist dynamically... i want that value should be the subject id and text should be the sub_desc...but code is not working the value does not contain the sub_ids...so whats wrong with the code??
(sub_id is integer field)
public void Populate()
{
string ConnectionString = (string)ConfigurationManager.AppSettings["ConnectionString"];
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand popCmd = new SqlCommand("select sub_id,sub_desc from subject", conn);
try
{
conn.Open();
ddlSub.Items.Clear();
SqlDataReader subs;
subs = popCmd.ExecuteReader();
ddlSub.DataSource = subs;
ddlSub.DataValueField = "sub_id";
ddlSub.DataTextField = "sub_des开发者_StackOverflowc";
ddlSub.DataBind();
conn.Close();
}
catch (Exception ex)
{
lblMsg.Visible = true;
lblMsg.Text = ex.ToString();
}
}
thanx...
You can set AppendDataBoundItems="true"
to ensure data bound items do not clear manually inserted list items.
<asp:DropDownList ID="DropDownList" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="--Select Subject--" Text="--Select Subject--" Selected="true"></asp:ListItem>
</asp:DropDownList>
You can also accomplish this in the code behind.
...
dropSub.Items.Add(new ListItem("--Select Subject--", "0"));
dropSub.AppendDataBoundItems = true;
SqlDataReader subs;
subs = popCmd.ExecuteReader();
ddlSub.DataSource = subs;
ddlSub.DataValueField = "sub_id";
ddlSub.DataTextField = "sub_desc";
ddlSub.DataBind();
conn.Close();
...
You can add you default after databinding. You will need to insert at an index of 0 though rather than Add.
精彩评论