c# – 使用类从asp.net中的数据库填充下拉列表的方法是什么?

我试图通过使用类来填充sql server中的下拉列表,如下所示.在将数据绑定到下拉列表时,代码会崩溃.它给dropdownlist提供了dataValueField和datatTextField的错误.

HTML … a.aspx

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

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

 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程序….

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

最佳答案 你的getNationality方法中的这行代码……

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

……应该是这样的

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

如果您的国籍表具有列ID和国籍,则数据绑定应该有效

点赞