【问题标题】:Populate dropdown from database in .Net从.Net中的数据库填充下拉列表
【发布时间】:2016-06-25 06:27:25
【问题描述】:

我的数据库代码:

USE Student
GO

CREATE PROCEDURE spDisplayCountry
AS
BEGIN
    SELECT countryName
    FROM CountryList
END

这段代码创建了一个我想从 C# 代码中使用的存储过程。

检索数据的C#代码:

protected void Page_Load(object sender, EventArgs e)
{
    // Connection String
    string constr = ConfigurationManager.ConnectionStrings["EmployeeContext"].ToString();    

    SqlConnection con = new SqlConnection(constr);
    con.Open();

    SqlCommand cmd = new SqlCommand("spDisplayCountry",con);
    cmd.CommandType = CommandType.StoredProcedure;

    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);    // Fill Dataset

    countryList.DataTextField = ds.Tables[0].Columns["countryName"].ToString();
    countryList.DataValueField = ds.Tables[0].Columns["countryId"].ToString(); // to retrieve specific text feild name.

    countryList.DataSource = ds.Tables[0];   // assigning Datasource to DropDown List
    countryList.DataBind();  // binding dropdown list.
}

【问题讨论】:

    标签: .net sql-server database


    【解决方案1】:

    您需要将要显示的列的 名称 分配给 DataTextFieldDataValueField - 而不是这些列的值 - 另外:如果您不检索,则无法分配 CountryId在你的存储过程中!

    应该是这样的

    countryList.DataTextField = "CountryName";
    countryList.DataValueField = "CountryId";
    

    您需要将存储过程更改为:

    CREATE PROCEDURE spDisplayCountry
    AS
    BEGIN
        SELECT CountryId, CountryName
        FROM dbo.CountryList
    END
    

    此外,如果您只检索一组数据(您通常会这样做),那么实例化 DataSet(可以保存几组相关数据)实际上没有任何意义 - 只需使用 DataTable

    DataTable dt = new DataTable();
    da.Fill(dt);    // Fill DataTable
    .....
    countryList.DataSource = dt; 
    countryList.DataBind(); 
    

    【讨论】:

    • 感谢@marc_s 的建议。
    猜你喜欢
    • 2011-11-09
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 2016-01-09
    相关资源
    最近更新 更多