Sunday, 15 September 2013

Convert DataTable to List in c#

There is very simple way to convert a datatable into generic list in c#. Have a look at the below steps -

Step 1 - Get the datatable, In my example datatable in containing three columns. Those are Name, Designation and Department.

Step 2 - Add a public class to your solution (Right click and add new items then chose class) to define the properties for the list.

public class PropertyClass
{
    private string name;
    public string Name
    {
        get{return name;}
        set { name = value; }
    }

    private string designation;
    public string Designation
    {
        get { return designation; }
        set { designation = value; }
    }

    private string department;
    public string Department
    {
        get { return department; }
        set { department = value; }
    }
}

Step 3 - Come to the page where conversion is required from datatable to list.
write the similar code as below -
let's say datatable which need to convert to list is dtMain.
   /// <summary>
    /// Method: Convert into list from datatable
    /// </summary>
    /// <returns></returns>
    private List<PropertyClass> GetListfromDataTable()
    {
        DataTable dtMain = GetDataTable();
        //List type object of the property class
        List<PropertyClass> propClass = new List<PropertyClass>();
        foreach (DataRow dr in dtMain.Rows)
        {
            //Object of the propery class
            PropertyClass objPC = new PropertyClass();
            //asign values
            objPC.Name = dr["Name"].ToString();
            objPC.Designation = dr["Designation"].ToString();
            objPC.Department = dr["Department"].ToString();

            //add one row to the list
            propClass.Add(objPC);
        }
        //return final list
        return propClass;
    }

Step 4 - Simple call this method, let's say on pageload
protected void Page_Load(object sender, EventArgs e)
    {
       //get datatable value into list on pageload
        List<PropertyClass> pc = GetListfromDataTable();
    }

Your feedback will be appreciated.

4 comments:

  1. thank you very much.. it is working fine and simple..

    ReplyDelete
  2. Hi ,
    Thanks For Solution, Please shares some more stuff on C# , if any..

    ReplyDelete
    Replies
    1. Hi, may be you would be interested to have few C# skilled test -
      http://vsstack.blogspot.in/p/blog-page.html

      Delete
  3. Thank you, it is working... really thanks (y)

    ReplyDelete