使用LINQ绑定数据表 [英] Bind datatable using LINQ
问题描述
我在我的asp.net应用程序中使用LINQ。我的应用程序有一个数据访问层,我必须在其中编写方法以将数据返回到datatable,并将该方法调用到UI以将数据表绑定到gridview。我正在使用sql过程绑定数据。
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.
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.
推荐答案
使用EF你将始终获得IEnumerable< ttype>< / ttype>
的对象。您可以编程将此对象转换为DataTable
,如下所示
Using EF you will always get object ofIEnumerable<ttype></ttype>
. You can convert this object toDataTable
programatically as below
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>
Hello.Maybe我可以帮到你:D
首先:这是数据访问层中的功能
Hello.Maybe I can help you :D
First : this is funtion in Data access layer
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
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:在网上展示
Finalny :Display on web
CustomerBus c = new CustomerBus(); // name of class BUS
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = c.customer();
GridView1.DataBind();
}
并在datacontext中实体化
完成它。
如果你不''了解你可以联系我。
$ b $bFacebook.Thắngcv
And entity it in datacontext
So it done.
If you don''t understand you can contact with me.
Facebook.Thắng cv
这篇关于使用LINQ绑定数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!