我正在从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相关问答推荐

如何在 C#/MVC 4 中的 Html.TextBoxFor 中输入占位符文本

如何从 ASP.NET 中的代码隐藏文件访问 IFRAME?

ASP .Net Web API 将图像下载为二进制

IIS HTTP 错误 500.19

如何在 ASP.NET 中以 'YYYY-MM-DD' 格式获取当前日期?

在 Sessions 中存储自定义对象

未知的网络方法.参数名称:methodName

为什么我在安装 IE8 后无法从 Visual Studio 2005 调试?

解析 JSON 响应的最简单方法

使用 JavaScript 更改 ASP.NET 标签的可见性

ASP.NET 在更新面板更新时显示正在加载...消息

N' 在 SQL 脚本中代表什么? (插入脚本中字符之前使用的那个)

如何在 ASP.NET 应用程序中使用 jQuery 捕获提交事件?

aspx 文件中的 if 语句

在 ASP.NET 中将虚拟路径转换为实际 Web 路径

尽管安装了 AspNetCoreModule,但在 IIS 中运行 ASP.NET Core 应用程序时出现 0x8007000d 错误 500.19

如何判断字符串的第一个字符是否是字母,C#中的任何字母

在 Asp.Net MVC 5 中获取登录用户的用户 ID

在控制器 asp.net-core 中获取当前区域性

MVC4 - 当优化设置为 true 时Bundle 不起作用