我正在使用以下代码过滤数据表,以显示包含我的电子邮件地址的元组。但是我一直收到Missing Operand after @
错误。
using (SqlConnection connection = new SqlConnection(conn))
{
connection.Open();
SqlCommand mycommand = new SqlCommand("select * from mytable",connection);
// SqlDataReader dataReader = mycommand.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(mycommand.ExecuteReader());
string value = "me@live.com";
DataView dv = new DataView(dt);
dv.RowFilter = "email = "+value;
dataGridView1.DataSource = dv.ToTable();
// dataGridView1.DataSource = dt;
}
答案 0 :(得分:1)
尝试一下。
using (SqlConnection connection = new SqlConnection(conn))
{
connection.Open();
var query = "select * from mytable WHERE email = 'me@live.com'";
SqlCommand mycommand = new SqlCommand(query,connection);
// SqlDataReader dataReader = mycommand.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(mycommand.ExecuteReader());
DataView dv = new DataView(dt);
dataGridView1.DataSource = dv.ToTable();
// dataGridView1.DataSource = dt;
}
答案 1 :(得分:1)
这里:
string value = "me@live.com";
DataView dv = new DataView(dt);
dv.RowFilter = "email = "+value;
您正在做的是
DataView dv = new DataView(dt);
dv.RowFilter = "email = me@live.com";
因此,您缺少将文字字符串括起来的撇号。您应该改用以下方法:
string value = "'me@live.com'";
因此生成的过滤器是:
dv.RowFilter = "email = 'me@live.com'";
由于您可能是从其他地方(而不是文件中的硬编码)获取电子邮件,因此,如果您使用的是C#6.0或更高版本,则可以这样做:
string value = "me@live.com";
DataView dv = new DataView(dt);
dv.RowFilter = $"email = '{value}'";
答案 2 :(得分:1)
为什么从数据库中提取全部数据后进行过滤?只需在查询本身中对其进行过滤即可:
从mytable中选择*,其中email ='me@live.com'
答案 3 :(得分:-1)
尝试一下,让我知道它是否有效
using (SqlConnection connection = new SqlConnection(conn))
{
connection.Open();
SqlCommand mycommand = new SqlCommand("select * from mytable",connection);
// SqlDataReader dataReader = mycommand.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(mycommand.ExecuteReader());
string value = "me@live.com";
DataView dv = new DataView(dt);
dv.RowFilter = "email LIKE %'" + value + "'%";
dataGridView1.DataSource = dv.ToTable();
// dataGridView1.DataSource = dt;
}