将对象列表设置为下拉列表数据源

时间:2013-06-28 15:21:26

标签: asp.net

我有这个方法:返回一个Category对象列表,我想把这个列表输出设置为c#中的下拉列表数据源,我该怎么做

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();
            }

        }

1 个答案:

答案 0 :(得分:1)

像这样:

dropdownList.DataSource = GetAllCategories();
dropdownList.DateTextField= "CategoryName";
dropdownList.DataValueField = "JobCategoryid";
dropdownList.DataBind();