0

我是 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 是空的。任何建议真的很感激。

4

3 回答 3

3

您必须在select中使用new来指定列。

试试这个:

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();
于 2013-09-20T07:19:28.993 回答
2

你应该使用AsDataView()方法:

GridView1.Visible = true;
GridView1.DataSource = tbl.AsDataView();
GridView1.DataBind();

无需考虑列数。

或者你也可以使用CopyToDataTable()方法

GridView1.Visible = true;
GridView1.DataSource = tbl.CopyToDataTable();
GridView1.DataBind();
于 2013-09-20T07:35:35.517 回答
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();
于 2013-09-20T07:39:34.837 回答