List of list bindings in Asp.net
I want to add a data and data textbox field to a dropdown from Lis. How can i do this?
So far I like it, but it got the error:
DataBinding: "System.String" does not contain a property named 'Cos_name'.
This is my data access layer:
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;
}
This is my form loading
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();
}
source to share
Dotnetom has a good answer. However, if you want to use a List anyway, you can still do it using the following approach:
Create a new class for your data ...
public class CourseDetailsClass
{
public string cos_ID { get; set; }
public string cos_name { get; set; }
}
And then change your GetAllCourseName method like this ...
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;
}
This should work for you as well. Then you can use this list as data source and now it can find TextDataField
and fields TextValueField
.
source to share
The problem is that your method GetAllCourseName
returns a list of strings that obviously have no properties cos_name
and cos_ID
. Instead, you can return the data table and bind it to the dropdown:
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"];
}
The method cannot be changed FillCourseName
.
source to share