我是LINQ&的新手通过LINQ填充GridView。请看我的代码:
SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["mas"]);
DataSet ds = new DataSet();
string Query = string.Empty;
private void Bind_LINQ_To_DataSet()
{
Query = "select * from dbo.Movie";
SqlDataAdapter da = new SqlDataAdapter(Query, connection);
da.Fill(ds, "dbo.Movie");
var tbl = from p in ds.Tables["dbo.Movie"].AsEnumerable()
where p.Field<int>("ID") == Convert.ToInt32(TextBox1.Text)
select p;
GridView1.Visible = true;
GridView1.DataSource = tbl;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
Bind_LINQ_To_DataSet();
}
我的GridVIew是空的。任何建议都非常感谢。
答案 0 :(得分:3)
您必须在选择中使用新来指定列。
试试这个:
var datasource = from r in ds.Tables["dbo.Movie"].AsEnumerable()
where r.Field<int>("ID") == Convert.ToInt32(TextBox1.Text)
select
new { FirstName = r.Field<String>("firstname"), LastName = r.Field<string>("lastname") };
或使用此:
GridView1.DataSource = tbl.CopyToDataTable();
答案 1 :(得分:2)
您应该使用 AsDataView() 方法:
GridView1.Visible = true;
GridView1.DataSource = tbl.AsDataView();
GridView1.DataBind();
无需考虑列数。
或者您也可以使用CopyToDataTable()
方法
GridView1.Visible = true;
GridView1.DataSource = tbl.CopyToDataTable();
GridView1.DataBind();
答案 2 :(得分:2)
这样做:
IEnumerable<DataRow> query =
from c in ds.Tables["dbo.Movie"].AsEnumerable()
where c.Field<int>("ID") == Convert.ToInt32(TextBox1.Text)
select c;
DataTable boundTable = query.CopyToDataTable<DataRow>();
GridView1.Visible = true;
GridView1.DataSource = boundTable ;
GridView1.DataBind();