本文介绍了使用类从asp.net中的数据库填充下拉列表的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试通过使用如下所示的类来从sql server中填充一个dropdownlist.将数据绑定到下拉列表时,代码会崩溃.在为下拉列表提供dataValueField和datatTextField时会出错.

I am trying to populate a dropdownlist from sql server by using classes as shown below. The code breaks down when it comes to bind the data into the dropdown list. It gives an error on giving the dropdownlist the dataValueField and datatTextField.

HTML ... a.aspx

HTML... a.aspx

<asp:DropDownList ID="NationalityDropDownList" runat="server"  >
</asp:DropDownList>

C#... a.aspx.cs

C#... a.aspx.cs

protected void Page_Load(object sender, EventArgs e)
    {
        Classes.Nationality PossibleNationality = new Classes.Nationality();
        if (!Page.IsPostBack)
        {              
            DataTable dataTable = PossibleNationality.getNationality();
            NationalityDropDownList.DataSource = dataTable;

            NationalityDropDownList.DataValueField = "ID";
            NationalityDropDownList.DataTextField = "Nationality";
            NationalityDropDownList.DataBind();
        }
    } 

Nationality.cs

Nationality.cs

 public class Nationality
 {
   public DataTable getNationality()
    {
        SqlConnection conn;
        SqlCommand comm;
        string  connectionString = ConfigurationManager.ConnectionStrings["InformationConnection"].ConnectionString;
        conn = new SqlConnection(connectionString);
        comm = new SqlCommand("spGetAllUsers", conn);
        comm.CommandType = CommandType.StoredProcedure;
        DataTable dataTable;
        try
        {
            conn.Open();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = comm;
            dataTable = new DataTable();
            da.Fill(dataTable);
        }
        finally
        {
            conn.Close();
        }
        return dataTable;
    }
}

SQL过程......

SQL procedure....

ALTER PROCEDURE [dbo].[spGetNationalities] 
AS
BEGIN
    select * from Nationality;
END

推荐答案

您的 getNationality 方法中的这一行代码...

This line of code in your getNationalitymethod...

comm = new SqlCommand("spGetAllUsers", conn);

...应该是这个

comm = new SqlCommand("spGetNationalities", conn);

如果您的 Nationality 表具有ID和Nationality列,则

数据绑定应该可以工作

Databinding should work if your Nationality table has columns ID and Nationality

这篇关于使用类从asp.net中的数据库填充下拉列表的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 04:47