How I can search rows in a datatable with a searchstring?

后端 未结 5 1125
清酒与你
清酒与你 2020-12-30 02:35

I want to search rows in my DataTable.

I\'ve tried this:

 protected void imggastsuche_Click(object sender, EventArgs e) 
        {
              


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-30 03:20

    You get the error because the parameter to Select is the filterExpression and you have passed all columns. Understand the filterExpression as a WHERE clause in sql. You want all columns but you want to filter by just one. You get all columns anyway since they are all part of the DataTable/DataView so you don't need to list them explicitely.

    You could either use the DataTable.Select, DatView.RowFilter methods or LINQ-to-DataSet:

    LINQ-To-DataSet (which i prefer):

    var filtered = tb.AsEnumerable()
        .Where(r => r.Field("CREATOR").Contains(searchstring));
    

    ADO.NET(DataTable.Select):

    DataRow[] filteredRows = tb.Select("CREATOR LIKE '%" + searchstring + "%'");
    

    ADO.NET(DataView.RowFilter):

     tb.DefaultView.RowFilter = "CREATOR LIKE '%" + searchstring + "%'";
    

    If you want to search for this string in any column instead:

    DataRow[] filteredRows = tb.Select("FIRSTNAME LIKE '%" + searchstring + "%' OR LASTNAME LIKE '%" + searchstring + "%' OR NAME LIKE '%" + searchstring + "%' OR COMPANY LIKE '%" + searchstring + "%' OR CREATOR LIKE '%" + searchstring + "%'");
    

    The same with Linq:

    var filtered = tb.AsEnumerable()
        .Where(r => r.Field("FIRSTNAME").Contains(searchstring)
               ||   r.Field("LASTNAME").Contains(searchstring))
               ||   r.Field("NAME").Contains(searchstring)
               ||   r.Field("COMPANY").Contains(searchstring)
               ||   r.Field("CREATOR").Contains(searchstring));
    

提交回复
热议问题