绑定列表下拉

本文关键字:列表 绑定 | 更新日期: 2023-09-27 18:04:50

我想添加数据文本字段和数据值字段从列表下拉列表。我该怎么做呢?

到目前为止,我喜欢这样做,但它得到了一个错误:

数据绑定:"系统。字符串'不包含带有名称的属性"cos_name"。

这是我的数据访问层:

public List<String> GetAllCourseName()
{
    SqlConnection objsqlconn = new SqlConnection(conn);
    objsqlconn.Open();
    SqlDataAdapter da = new SqlDataAdapter("select cos_ID, cos_name from course_details", objsqlconn); 
    DataSet ds = new DataSet(); 
    da.Fill(ds, "course_details"); 
    List<String> courseName = new List<String>();
    foreach(DataRow row in ds.Tables["course_details"].Rows)
    {
        courseName.Add(row["cos_ID"].ToString());
        courseName.Add(row["cos_name"].ToString());
    }
    return courseName;
}

这是我的Form load

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        FillCourseName();
    }   
}
public void FillCourseName()
{
    ddcoursename.DataSource = objda.GetAllCourseName();
    ddcoursename.DataTextField = "cos_name";
    ddcoursename.DataValueField = "cos_ID";
    ddcoursename.DataBind();
}

绑定列表下拉

Dotnetom给出了一个很好的答案。但是,如果您仍然希望使用List,您仍然可以采用另一种方法,如:

为你的数据创建一个新的类

public class CourseDetailsClass
{
    public string cos_ID { get; set; }
    public string cos_name { get; set; }
}

然后像这样修改你的GetAllCourseName方法…

public List<CourseDetailsClass> GetAllCourseName()
{
   SqlConnection objsqlconn = new SqlConnection(conn);
   objsqlconn.Open();
   SqlDataAdapter da = new SqlDataAdapter("select cos_ID, cos_name from course_details", objsqlconn); 
   DataSet ds = new DataSet(); 
   da.Fill(ds, "course_details"); 
   List<CourseDetailsClass> courseName = new List<CourseDetailsClass>();
   foreach(DataRow row in ds.Tables["course_details"].Rows)
   {
        courseName.Add(new CourseDetailsClass
        {
            cos_ID = row["cos_ID"].ToString(),
            cos_name = row["cos_name"].ToString()
        });         
    }
     return courseName;
}

这应该也适用于你。然后,您可以使用列表作为数据源,现在它将能够找到TextDataFieldTextValueField字段。

问题是你的方法GetAllCourseName返回字符串列表,显然没有属性cos_namecos_ID。相反,您可以返回一个数据表并将其绑定到一个下拉列表:

public DataTable GetAllCourseName()
{
   SqlConnection objsqlconn = new SqlConnection(conn);
   objsqlconn.Open();
   SqlDataAdapter da = new SqlDataAdapter("select cos_ID, cos_name from course_details", objsqlconn); 
   DataSet ds = new DataSet(); 
   da.Fill(ds, "course_details"); 
   return ds.Tables["course_details"];
}

不需要更改FillCourseName方法