Convert DataTable to List

This article describes how to convert data in datatable to List. We are already discussed about how to create and store data in the datatable, for to get details please follow the link Click here.

first create  datatable with its columns and call that method in page load.
e.g.

private void tempattributetable()
{
DataTable dt = new DataTable();
dt.Columns.Add("Image_Path ", typeof(int));
dt.Columns.Add("ItemDetail_ID ", typeof(string));
dt.Columns.Add("IsDefaultImage ", typeof(string));
Session["dt"] = dt;
}

Then create a class file and write the parameters.
e.g.:

public class MyType
{
public string Image_Path { get; set; }
public int ItemDetail_ID { get; set; }
public bool IsDefaultImage { get; set; }
}

Follow the below coding for converting datatable to list format.

private void BindGrid()
{
DataTable dtimg = (Session["dt"]) as DataTable;
List<MyType> list = new List<MyType>();
var imgList = (from DataRow dr in dtimg.Rows
select new MyType()
{
Image_Path = dr["Image_Path"].ToString(),
ItemDetail_ID = Convert.ToInt32(dr["ItemDetail_ID"].ToString()),
IsDefaultImage = Convert.ToBoolean(dr["IsDefaultImage"].ToString())
}).ToList();
}

Post a Comment

0 Comments