简体   繁体   English

如何在C#Windows窗体中使用文本框过滤DataGridView

[英]How to filter DataGridView using a textbox in C# Windows Form

I found a problem on how to filter the list that I have in the data grid view of my the Windows Form. 我发现有关如何过滤Windows窗体的数据网格视图中的列表的问题。

Basically, I have a textbox and I want that when I enter value in it, it will filter the Data Grid View. 基本上,我有一个文本框,当我在其中输入值时希望它会过滤数据网格视图。

I do not have any errors, but when I try to write text in the text box, the grid view remains the same and does not filter anything. 我没有任何错误,但是当我尝试在文本框中写入文本时,网格视图保持不变并且不过滤任何内容。

The following is my FormLoad (Where it fills the gridview) 以下是我的FormLoad(在其中填充gridview的地方)

private void Transactions_Load(object sender, EventArgs e)
    {
        List<LogsViewModel> logs = sr.GetTransactions().ToList();
        dgvTransactions.DataSource = sr.GetTransactions().ToList();
    }

The following is when I input text in the textbox: 以下是我在文本框中输入文本的时间:

private void txtAccountID_TextChanged(object sender, EventArgs e)
    {
        BindingSource bs = new BindingSource();
        bs.DataSource = dgvTransactions.DataSource;
        bs.Filter = dgvTransactions.Columns[1].HeaderText.ToString() + " LIKE '%" + txtAccountID.Text + "%'";
        dgvTransactions.DataSource = bs.DataSource;
    }

Please help! 请帮忙! Thanks 谢谢

You need to call the DataBind() method in your txtAccountID_TextChanged() event. 您需要在txtAccountID_TextChanged()事件中调用DataBind()方法。

private void txtAccountID_TextChanged(object sender, EventArgs e)
    {
        BindingSource bs = new BindingSource();
        bs.DataSource = dgvTransactions.DataSource;
        bs.Filter = dgvTransactions.Columns[1].HeaderText.ToString() + " LIKE '%" + txtAccountID.Text + "%'";
        dgvTransactions.DataSource = bs.DataSource;
        dgvTransactions.DataBind();
    }

I'm not in a position to test this, but it still might not update until you press the Enter key or cause the TextBox to lose focus. 我无法对此进行测试,但是直到您按Enter键或使TextBox失去焦点之前,它可能仍不会更新。

 private void txtAccountID_TextChanged(object sender, EventArgs e) { (dgvTransactions.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", textBoxFilter.Text); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM