Tarasov Tarasov - 1 year ago 68
C# Question

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

hi I want to search rows in my DataTable for this I try this:

protected void imggastsuche_Click(object sender, EventArgs e)
string searchstring = txtgastsuche.Text;

DataTable tb = DataBaseManager.GetDataTable(mysqlconnectionstring);

DataRow[] foundRows = tb.Select("FIRSTNAME,LASTNAME,NAME,COMPANY,TIMEFROM,TIMETO,CREATOR Like '%" + searchstring + "%'");

tb = foundRows.CopyToDataTable();

this.ListView.DataSource = tb;


But I have a error in my string . what can I do if I want search this columns?

Answer Source

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<String>("CREATOR").Contains(searchstring));


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


 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<String>("FIRSTNAME").Contains(searchstring)
           ||   r.Field<String>("LASTNAME").Contains(searchstring))
           ||   r.Field<String>("NAME").Contains(searchstring)
           ||   r.Field<String>("COMPANY").Contains(searchstring)
           ||   r.Field<String>("CREATOR").Contains(searchstring));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download