linq查询数据未显示错误

时间:2013-12-17 09:53:59

标签: c# asp.net linq gridview

我正在尝试使用LINQ查询将数据从DataTable显示到GridView中,但我无法理解为什么此代码无效。实际上GridView显示 RowError HasError 消息。我完全糊涂了。

这是我的代码

protected void Page_Load(object sender, EventArgs e)
{
    DataTable table = (DataTable)Session["userTable"];
    string compare = Request.QueryString["id"].ToString();
    var data = from x in table.AsEnumerable()
               where x.Field<string>("Userid") == compare
               select x;
    GridView1.DataSource = data;
    GridView1.DataBind();
}

2 个答案:

答案 0 :(得分:2)

您的查询返回IEnumerable<DataRow>以将其转换为Datatble使用CopyToDataTable()扩展名。 MSDN

protected void Page_Load(object sender, EventArgs e)
{
    DataTable table = (DataTable)Session["userTable"];
    string compare = Request.QueryString["id"].ToString();
    IEnumerable<DataRow> data = from x in table.AsEnumerable()
                                where x.Field<string>("Userid") == compare
                                select x;

    DataTable boundTable = data.CopyToDataTable<DataRow>();
    GridView1.DataSource = boundTable;
    GridView1.DataBind();
}

答案 1 :(得分:1)

试试这个,

var data = from x in table.AsEnumerable()
                    where x.Field<string>("UserId").ToUpper().ToString().Equals(compare.ToUpper().ToString())
                    select x;

        DataTable boundTable = data.AsDataView().ToTable();
        return boundTable;