Search code examples
c#sqlsql-serverdatatabledataview

Filtering Datatable -Missing operand after @


I'm using the following code to filter a datatable to show tuples that contain my email address.But i keep getting Missing Operand after @ Error.

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;
}

Solution

  • Here:

    string value = "me@live.com";
    DataView dv = new DataView(dt);
    dv.RowFilter = "email = "+value;
    

    What you are doing is:

    DataView dv = new DataView(dt);
    dv.RowFilter = "email = me@live.com";
    

    Therefore you are missing the apostrophes to enclose the literal string. You should use this instead:

    string value = "'me@live.com'";
    

    So the resulting filter is:

    dv.RowFilter = "email = 'me@live.com'";
    

    As you are probably getting the email from somewhere else (instead of hardcoded in your file), if you are using C# 6.0 or greater, you could do this instead:

    string value = "me@live.com";
    DataView dv = new DataView(dt);
    dv.RowFilter = $"email = '{value}'";