如何使用searchstring搜索数据表中的行? [英] How I can search rows in a datatable with a searchstring?

查看:198
本文介绍了如何使用searchstring搜索数据表中的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的DataTable中搜索行,我尝试这样:

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;
            this.ListView.DataBind();

        }

但是我的字符串中有错误。

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

推荐答案

您的错误是因为选择 filterExpression ,并且已经传递了所有列。在sql中了解filterExpression作为 WHERE 子句。你想要所有的列,但你只想过滤一个。由于它们都是 DataTable / DataView 的所有部分,所以您不需要列出它们

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.

您可以使用 DataTable.Select DatView.RowFilter 方法或 LINQ to to DataSet

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

LINQ-To-DataSet(我喜欢):

LINQ-To-DataSet (which i prefer):

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

ADO.NET( DataTable.Select ) :

ADO.NET(DataTable.Select):

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

ADO.NET( DataView.RowFilter ) :

ADO.NET(DataView.RowFilter):

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






如果要搜索此 string 改为:

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

与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));

这篇关于如何使用searchstring搜索数据表中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆