Click here to Skip to main content
15,886,756 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello all

I am newbie here.

I have a View in SQL. I use LINQ for my project winform - C#.

C#
DataContext db = new DataContext();

I can return that view for my GridControl.

C#
public static GridControl getUserTable(GridControl DSNV)
{
            try
            {
                var f = db.viewUserTables;
                DSNV.DataSource = f;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
            return DSNV;
}


This code only return type GridControl, but i need use it for something else(Lookup...) Now, i want it can return type
C#
DataTable
.

How i can do it?

Sorry, my english very bad.
Posted

1 solution

Hi,


Just add this extension method.

public static DataTable ToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection props =
        TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for(int i = 0 ; i < props.Count ; i++)
    {
        PropertyDescriptor prop = props[i];
        table.Columns.Add(prop.Name, prop.PropertyType);
    }
    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;        
}


How to Use

var f = db.viewUserTables.ToDataTable();
 
Share this answer
 
v2
Comments
GinCanhViet 9-Jun-14 0:59am    
thank you so much, i will try it.
GinCanhViet 9-Jun-14 1:00am    
Can not call var f = db.viewUserTables''.ToDataTable()''
Suvabrata Roy 9-Jun-14 3:44am    
Can not call var f = db.viewUserTables.ToDataTable();

There is no double cote
That was a extension method use it like a method.
You know what is a extension method?
GinCanhViet 9-Jun-14 20:25pm    
Hehe, your solution very trouble.
I've solved this myself!

Thank you!
Suvabrata Roy 10-Jun-14 0:24am    
Ok that's fine but why my solution gives you trouble, you need any kind of clarification of my code ?

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