我正在尝试通过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();
}
}
}
答案 0 :(得分: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();
BTW为什么不将Linq用于实体?您将能够在数据库端进行过滤。