How can I populate a drop-down list from a database in asp.net using classes?

I am trying to populate a drop down list from a SQL server using classes as shown below. The code breaks when it comes to binding data to a drop-down list. It gives an error when providing the dropdown list dataValueField and 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 procedure ....

ALTER PROCEDURE [dbo].[spGetNationalities] 
AS
BEGIN
    select * from Nationality;
END
+4
source share
1 answer

This line of code in your method getNationality...

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

... should be this instead

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

Data binding should work if your table Nationalityhas column identifiers and nationality

+2
source

All Articles