如何使用C#中的文本框过滤datagridview? [英] How to filter datagridview using a textbox in C#?

查看:99
本文介绍了如何使用C#中的文本框过滤datagridview?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我厌倦了使用文本框过滤datagridview,文本框包含在标签页中,但它不起作用,这里是代码:

I tired to filter a datagridview using a textbox, the textbox is contained in a tabpage, but it is not working, here is the code :

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        try
        {
            ((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = "like '%" + textBox1.Text.Trim() + "%' ";
        }
        catch (Exception) { }

    }


推荐答案

RowFilter 允许您根据列值指定过滤器。因此, LIKE 适用于特定列,而不适用于整行。所以你的条件应该是

RowFilter allows you to specify a filter based on column values. So the LIKE applies to a specific column, not to the whole row. So your condition should be

"YourColumn like '%" + textBox1.Text.Trim() + "%'

另外,不要忘记,TextBox可能包含'字符,所以你需要逃脱:

Also, don't forget that the TextBox could contain the ' character, so you need to escape it:

"YourColumn like '%" + textBox1.Text.Trim().Replace("'", "''") + "%'

或者, p>

Or, cleaner:

string.Format("YourColumn like '%{0}%'", textBox1.Text.Trim().Replace("'", "''"));

这篇关于如何使用C#中的文本框过滤datagridview?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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