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

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

问题描述

我想在我的 DataTable 中搜索行.

I want to search rows in my DataTable.

我已经试过了:

 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 an error in my string.

如果我想搜索这些列,我该怎么做?

What can I do if I want to search these columns?

推荐答案

您收到错误,因为 Select 的参数是 filterExpression 并且您已通过所有列.将 filterExpression 理解为 sql 中的 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-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):

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

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

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

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