通过按键过滤datagridview中的行 [英] Filter rows in datagridview by key press

查看:51
本文介绍了通过按键过滤datagridview中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,该代码将用户限制为只能在文本框中键入数字.

然后我如何使用键入的数值来匹配 driverNo 文本框中的内容,从而过滤datagrid( dataGridView1 )中的行?是在 DriverNo 列中?

到目前为止,这是我的代码:

  private void driverNo_KeyPress(对象发送者,KeyPressEventArgs e){if(!char.IsControl(e.KeyChar)&&!char.IsDigit(e.KeyChar)){e.Handled = true;}} 

解决方案

您可以使用此代码隐藏所有具有与文本框中数字相同的行(我们将其称为 textBox1 ).

>

  foreach(dataGridView1.Rows中的DataGridViewRow行){如果(row.Cells ["driverNo"].Value!= null&&row.Cells ["driverNo"].Value.ToString()== textBox1.Text){row.Visible = false;}} 

请注意,如果您的 DataGridView 已绑定到DataSet,则应该首先需要暂停数据绑定.

如果希望在用户键入时(即时)进行过滤,可以将此代码附加到 KeyUp 事件:

  private void textBox1_KeyUp(对象发送者,KeyEventArgs e){foreach(dataGridView1.Rows中的DataGridViewRow行){如果(row.Cells ["driverNo"].Value!= null&&row.Cells ["driverNo"].Value.ToString()== textBox1.Text){row.Visible = false;}别的{row.Visible = true;}}} 

您可以使用查找或哈希表来优化此代码以消除循环.但这基本上可以正常工作(尚未在大数据网格上进行测试).

I've got the following code which restricts the user to typing only numbers into a textbox.

How would I then use the numerical values that are typed in to filter the rows in my datagrid (dataGridView1) by matching what is written in the driverNo textbox to what is in the DriverNo column?

This is my code so far:

private void driverNo_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
}

解决方案

You can use this code to hide all rows that have the number as in your textbox (let's call it textBox1).

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.Cells["driverNo"].Value != null
        && row.Cells["driverNo"].Value.ToString() == textBox1.Text)
    {
        row.Visible = false;
    }
}

Note that if your DataGridView is bounded to DataSet you should first need to suspend data binding.

EDIT:

If you want the filtering to occur while user typing (on the fly), you can attach this code to the KeyUp event:

private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.Cells["driverNo"].Value != null
            && row.Cells["driverNo"].Value.ToString() == textBox1.Text)
        {
            row.Visible = false;
        }
        else
        {
            row.Visible = true;
        }
    }
}

You can optimize this code to eliminate the loop with the use of lookup or hash table. But this basically works fine (have not tested on big data grid).

这篇关于通过按键过滤datagridview中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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