Reputation: 187
I have this method: that returns a list of Category object , and i want to set this list output as Drop down list Datasource in c# , how can i do that
public List<Category> GetAllCategories()
{
SqlConnection con = new SqlConnection(connectonstring);
SqlCommand cmd = new SqlCommand("GetAllCategories", con);
cmd.CommandType = CommandType.StoredProcedure;
List<Category> Categories = new List<Category>();
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Category cat = new Category();
cat.JobCategoryid = Convert.ToInt32(reader["JobCategoryid"]);
cat.CategoryName = reader["categoryName"].ToString();
Categories.Add(cat);
}
reader.Close();
return Categories;
}
catch (SqlException err)
{
return null;
}
finally
{
con.Close();
}
}
Upvotes: 0
Views: 3395
Reputation: 63956
Like this:
dropdownList.DataSource = GetAllCategories();
dropdownList.DateTextField= "CategoryName";
dropdownList.DataValueField = "JobCategoryid";
dropdownList.DataBind();
Upvotes: 1