Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I want to convert DataTable to object type List in C#. for the i have written the following code. But it is not working. Please help me

C#
public List<object> ShowMessage()
   {
       List<object> obj = new List<object>();

       DataTable dt = new DataTable();
       dt.Columns.Add("ID");
       dt.Columns.Add("Name");

       dt.Rows.Add("1","AAA");
       dt.Rows.Add("2", "BBB");
       dt.Rows.Add("3", "CCC");

       foreach (DataRow dr in dt.Rows)
       {

           obj.Add(dr);
       }

       return obj;
   }



NB:Just i want to convert a datatable to a list.You may not consider my above code.Just give me the code to convert a DataTable to a List. I am using .Net Framework 4.0


Thanks in advance
Rashed
Posted
Updated 10-Oct-12 21:46pm
v2
Comments
n.podbielski 11-Oct-12 3:11am    
And how exactly it is not working? Can you paste some errors? What is desired behavior?
Sergey Alexandrovich Kryukov 11-Oct-12 3:11am    
List<object> is in fact untyped list (as everything is object), normally, totally pointless.
In your sample, it should be List<DataRow>. (But why?!)
Just a note.
--SA

Can you try something like this:
C#
List<object> lst = dt.AsEnumerable().ToList<object>();



--Amit
 
Share this answer
 
v2
Comments
[no name] 11-Oct-12 3:43am    
Not working..
_Amy 11-Oct-12 4:32am    
Check the link below:
http://s9.postimage.org/ts5ca0sq7/Untitled.png[^]
Here I used same code.
Member 11868427 28-Mar-19 12:39pm    
Not working
Member 14566376 30-Aug-19 11:33am    
No
This is how you should correctly add a data row:
http://msdn.microsoft.com/en-us/library/system.data.datatable.rows.aspx[^].

Besides, your code looks totally pointless. And hard coded immediate constants like "ID", "Name" is evil. This style makes code unsupportable. However, I would understand if you are just experimenting.

—SA
 
Share this answer
 
hi
try this

XML
public static List<Object> ConvertRowsToList<Object>( DataTable input, Convert<DataRow, Object> conversion) {
    List<Object> Objval = new List<Object>()
    foreach(DataRow dr in input.Rows)
        Objval.Add( conversion(dr) );

    return Objval;
}
 
Share this answer
 
XML
public static IList<object> ConvertTo<object>(DataTable table)
    {
        if (table == null)
            return null;

        List<DataRow> rows = new List<DataRow>();

        foreach (DataRow row in table.Rows)
            rows.Add(row);

        return ConvertTo<object>(rows);
    }
 
Share this answer
 
Comments
[no name] 11-Oct-12 4:05am    
ConvertTo<object>(rows) is not working...
Member 12639919 26-Jul-16 7:18am    
Aahaan

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900