什么是填充从数据库中一个DropDownList的正确方法? [英] What is the right way to populate a DropDownList from a database?

查看:95
本文介绍了什么是填充从数据库中一个DropDownList的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从填充SQL Server数据库DropDownList中,如下图所示。它工作正常,但我不知道这是一个很好的方式。有人可以阐明这个方法有些轻,并给予一定的改善呢?

 私人无效LoadSubjects()
{
    ddlSubjects.Items.Clear();
    字符串selectSQL =SELECT SubjectID,主旨名称FROM Students.dbo.Subjects    SqlConnection的CON =新的SqlConnection(的connectionString);
    CMD的SqlCommand =新的SqlCommand(selectSQL,CON);
    SqlDataReader的阅读器;    尝试
    {
        列表项的newitem =新的ListItem();
        newItem.Text =<选择主题>中;
        newItem.Value =0;
        ddlSubjects.Items.Add(的newitem);        con.Open();
        读者= cmd.ExecuteReader();
        而(reader.Read())
        {
            的newitem =新的ListItem();
            newItem.Text =读卡器[主旨名称]的ToString()。
            newItem.Value =读卡器[SubjectID]的ToString()。
            ddlSubjects.Items.Add(的newitem);
        }
        reader.Close();
    }
    赶上(例外错误)
    {
        //去做
    }
    最后
    {
        con.Close();
    }
}


解决方案

您可以将DropDownList绑定到数据源(数据表,表,数据集,SqlDataSource的,等等)。

例如,如果你想使用一个DataTable:

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

编辑 - 更完整的例子

 私人无效LoadSubjects()
{    数据表科目=新的DataTable();    使用(SqlConnection的CON =新的SqlConnection(的connectionString))
    {        尝试
        {
            SqlDataAdapter的适配器=新的SqlDataAdapter(SELECT SubjectID,主旨名称FROM Students.dbo.SubjectsCON);
            adapter.Fill(学科);            ddlSubject.DataSource =科目;
            ddlSubject.DataTextField =SubjectNamne;
            ddlSubject.DataValueField =SubjectID;
            ddlSubject.DataBind();
        }
        赶上(异常前)
        {
            //处理错误
        }    }    //添加初始项目 - 所以即使从选项添加此
    // DB没有成功加载
    ddlSubject.Items.Insert(0,新的ListItem(&下;选择主体>中,0));}

要通过标记设置初始值,而不是code-背后,指定选项(S),并设置AppendDataBoundItems属性为true:

 < ASP:DropDownList的ID =ddlSubject=服务器AppendDataBoundItems =真>
    < ASP:ListItem的文本=<选择主题>中值=0/>
< / ASP:DropDownList的>

然后,您可以将DropDownList绑定到code-背后一个DataSource(只记得删除:

  ddlSubject.Items.Insert(0,新的ListItem(<选择主题>中,0));

从code-后面,否则你将有两个,项目。

I am populating a DropDownList from a SQL Server database as shown below. It works fine, but I'm not sure it's a good way. Can someone shed some light on this method, and give some improvements?

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

解决方案

You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).

For example, if you wanted to use a 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"));

}

To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:

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

You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:

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

from the code-behind, or you'll have two "" items.

这篇关于什么是填充从数据库中一个DropDownList的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆