我正在从SQL Server数据库填充DropDownList,如下所示.这很好,但我不确定这是不是一个好方法.有人能解释一下这个方法,并给出一些改进吗?

private void LoadSubjects()
{
    ddlSubjects.Items.Clear();
    string selectSQL = "SELECT SubjectID,SubjectName FROM Students.dbo.Subjects";

    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand(selectSQL, con);
    SqlDataReader reader;

    try
    {
        ListItem newItem = new ListItem();
        newItem.Text = "<Select Subject>";
        newItem.Value = "0";
        ddlSubjects.Items.Add(newItem);

        con.Open();
        reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            newItem = new ListItem();
            newItem.Text = reader["SubjectName"].ToString();
            newItem.Value = reader["SubjectID"].ToString();
            ddlSubjects.Items.Add(newItem);
        }
        reader.Close();
    }
    catch (Exception err)
    {
        //TODO
    }
    finally
    {
        con.Close();
    }
}

推荐答案

您可以将DropDownList绑定到数据源(DataTable、List、DataSet、SqlDataSource等).

例如,如果要使用DataTable:

ddlSubject.DataSource = subjectsTable;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();

EDIT - More complete example

private void LoadSubjects()
{

    DataTable subjects = new DataTable();

    using (SqlConnection con = new SqlConnection(connectionString))
    {

        try
        {
            SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);
            adapter.Fill(subjects);

            ddlSubject.DataSource = subjects;
            ddlSubject.DataTextField = "SubjectNamne";
            ddlSubject.DataValueField = "SubjectID";
            ddlSubject.DataBind();
        }
        catch (Exception ex)
        {
            // Handle the error
        }

    }

    // Add the initial item - you can add this even if the options from the
    // db were not successfully loaded
    ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));

}

要通过标记(而不是代码隐藏)设置初始值,请指定选项并将Append数据边界Items属性设置为true:

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

然后,您可以将DropDownList绑定到代码隐藏中的数据源(只需记住删除:

ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));

从代码隐藏,否则您将有两个""项.

Asp.net相关问答推荐

您如何处理多个环境的多个 web.config 文件?

我可以在一个 Web 项目中有多个 web.config 文件吗?

httpCompression 和 urlCompression 有什么区别?

HttpResponse 的区别:SetCookie、AppendCookie、Cookies.Add

如何使用 SmtpClient.SendAsync 发送带有附件的邮箱?

登录成功后 User.Identity.IsAuthenticated 为 false

System.Web.Helpers.Crypto - 盐在哪里?

如何在页面的基类中执行 Page_Load()?

如何计算/查找给定日期的周数?

倒带请求正文流

如何将 Web 应用程序项目转换为类库项目

如何从 URI 中删除 PROTOCOL

asp.net cookie、身份验证和会话超时

如何配置 ASP.NET Core 1.0 以使用本地 IIS 而不是 IIS Express?

最佳服务器端 .NET PDF 编辑库

GridView 与嵌套类的属性绑定

MVC5 身份验证中的......与主域之间的信任关系失败

ContentResult 与字符串

ASP.Net 哪个用户帐户在 IIS 7 上运行 Web 服务?

使用 jQuery 从 asp:RadioButtonList 读取选定的值