小编典典

从数据库填充DropDownList的正确方法是什么?

c#

我正在从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();
    }
}

阅读 434

收藏
2020-05-19

共1个答案

小编典典

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

例如,如果您想使用数据表:

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

编辑-更完整的示例

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"));

}

要通过标记而不是代码隐藏设置初始值,请指定选项并将AppendDataBoundItems属性设置为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"));

从后面的代码中,否则您将有两个“”项。

2020-05-19