簡體   English   中英

綁定列表以在Asp.net中下載

[英]Bind list to drop down in Asp.net

我想從Lis下拉列表中添加數據文本字段和數據值字段。 我怎樣才能做到這一點?

到目前為止,我確實喜歡這個,但它有一個錯誤:

DataBinding:'System.String'不包含名為'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;
}

這是我的表單加載

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方法不需要更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM