Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 按键筛选datagridview中的行_C#_Winforms_Datagridview - Fatal编程技术网

C# 按键筛选datagridview中的行

C# 按键筛选datagridview中的行,c#,winforms,datagridview,C#,Winforms,Datagridview,我有下面的代码,它限制用户只在文本框中键入数字 然后,如何使用键入的数值将driverNo文本框中写入的内容与driverNo列中的内容相匹配,从而过滤我的datagrid(dataGridView1)中的行 这是我目前的代码: private void driverNo_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyC

我有下面的代码,它限制用户只在文本框中键入数字

然后,如何使用键入的数值将driverNo文本框中写入的内容与driverNo列中的内容相匹配,从而过滤我的datagrid(dataGridView1)中的行

这是我目前的代码:

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

您可以使用此代码隐藏文本框中包含数字的所有行(我们称之为
textBox1

请注意,如果您的
DataGridView
绑定到数据集,则首先需要挂起数据绑定

编辑:

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

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

您可以使用查找或哈希表优化此代码以消除循环。但这基本上运行良好(尚未在大数据网格上测试)

为了确保我理解,如果行包含按下的数字键,您想过滤显示的行吗?是的,但仅在DriverNo列中您可以检查
SelectedColumns
文本。是否包含按下的
DriverNo
键。我想你的文本框应该有一个提交按钮。或者,您希望在用户键入时即时执行此操作?如果是第二种情况,那么我想你应该处理相反的情况,即显示行。它必须在运行中发生
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;
        }
    }
}