2

我正在尝试通过 Linq 在我的数据表上过滤记录,但不知何故,结果是在表的列中显示一个没有错误的表,但一行显示“行有错误”。我的代码如下:有什么建议吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;


namespace linq_app
{
    public partial class admins : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcon"].ToString());

            con.Open();

            SqlCommand sqlcmd = new SqlCommand();
            sqlcmd.CommandText = "select * from user_info";
            sqlcmd.CommandType = CommandType.Text;

            sqlcmd.Connection = con;
            SqlDataReader sqlreader = sqlcmd.ExecuteReader();

            DataTable dt = new DataTable();
            dt.Columns.Add("first_name", typeof(string));
            dt.Columns.Add("last_name", typeof(string));
            dt.Columns.Add("Email_ID", typeof(string));
            dt.Columns.Add("Contact", typeof(string));
            dt.Columns.Add("Address", typeof(string));
            dt.Columns.Add("Role", typeof(string));


            while (sqlreader.Read())
            {
                DataRow dr = dt.NewRow();
                dr["first_name"] = sqlreader["first_name"];
                dr["last_name"] = sqlreader["last_name"];
                dr["Email_ID"] = sqlreader["email"];
                dr["Contact"] = sqlreader["contact1"];
                dr["Address"] = sqlreader["address"];
                dr["Role"] = sqlreader["role"];
                dt.Rows.Add(dr);
            }


            var results = from myRow in dt.AsEnumerable()
                          where myRow.Field<string>("Role").ToString() == "admin".ToString()
                          select myRow;

            //dataGridView1.DataSource = dt;


            //DataClasses1DataContext dc = new DataClasses1DataContext();
            //var admin = from records in dc.GetTable<user_info>() 
            //              where records.role =="admin"
            //              select records;
            GridView1.DataSource = results;
            GridView1.DataBind();
        }
    }
}
4

1 回答 1

3

尝试删除ToString呼叫。null如果角色列中有,它将抛出异常。并从过滤的行创建新的数据表:

var results = from myRow in dt.AsEnumerable()
              where myRow.Field<string>("Role") == "admin"
              select myRow;

GridView1.DataSource = results.CopyToDataTable(); // create datatable
GridView1.DataBind();

顺便说一句,为什么不使用 Linq to Entities 呢?您将能够在数据库端进行过滤。

于 2013-03-07T12:46:26.437 回答