Click here to Skip to main content
15,889,900 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using LINQ in my asp.net application. My application has a data access layer in which I have to write the method to return data to datatable and call that method into the UI to bind data table to gridview. I am using sql procedure to bind the data.

C#
public DataTable ViewUsers()
        {
            UsersDataContext db = new UsersDataContext();
            DataTable dt = new DataTable();
            var result = db.usp_ViewUser();
            // here I want to bind to the datatable
            return dt;
        }

Any one can give sample code to do that.
Posted
Updated 14-May-13 19:32pm
v2

Using EF you will always get object of IEnumerable<ttype></ttype>. You can convert this object to DataTable programatically as below

C#
public static DataTable ToDataTable<t>(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;        
}
</t></t>
 
Share this answer
 
Hello.Maybe I can help you :D
First : this is funtion in Data access layer
XML
   DataLinqDataContext db=new DataLinqDataContext();
    public List<Customer> customer()
    {
       List<Customer> newlist=new List<Customer>();
       var c=db.Sploadcustomer(); //sploadcustomer is name store procedure
//this is field i want.
       foreach (var item in c)
       {
           Customer cus = new Customer();
           cus.CustomerID = item.CustomerID;
           cus.CompanyName = item.CompanyName;
           cus.City = item.City;
           newlist.Add(cus);
       }
       return newlist;

   }

Second : this is funtion in Bussiness
XML
 Dataacces ac=new Dataacces //dataacces is name of class Data access
public List<Customer> customer() //<customer> is table in Database
{
    return ac.customer();
}</customer>

Finalny :Display on web
C#
CustomerBus c = new CustomerBus(); // name of class BUS
        protected void Page_Load(object sender, EventArgs e)
        {

            GridView1.DataSource = c.customer();
            GridView1.DataBind();
        }

And entity it in datacontext
So it done.
If you don't understand you can contact with me.
Facebook.Thắng cv
 
Share this answer
 
v2

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