动态填充下拉列表

时间:2009-11-26 14:31:03

标签: c# asp.net drop-down-menu

我使用以下代码动态填充下拉列表... 我希望该值应该是主题id和文本应该是sub_desc ...但代码不工作的值不包含sub_ids ...所以什么是错误的代码?

(sub_id是整数字段)

 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_desc";
                ddlSub.DataBind();
                conn.Close();
            }
            catch (Exception ex)
            {
               lblMsg.Visible = true;
               lblMsg.Text = ex.ToString();

            }

        }

...感谢名单

2 个答案:

答案 0 :(得分:3)

您可以设置AppendDataBoundItems="true"以确保数据绑定项不会清除手动插入的列表项。

<asp:DropDownList ID="DropDownList" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Value="--Select Subject--" Text="--Select Subject--" Selected="true"></asp:ListItem>
</asp:DropDownList>

您也可以在后面的代码中完成此操作。

...
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();
...

答案 1 :(得分:0)

您可以在数据绑定后添加默认值。您需要插入索引为0而不是Add。