如何通过在datagridview中键入charachters来关注单元格C# [英] How to focus on cell by typing charachters in datagridview C#

查看:75
本文介绍了如何通过在datagridview中键入charachters来关注单元格C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想专注于包含压缩字符的单元格。



假设datagridview包含两列名称和地址。

现在进入名称列有很多记录像Nims,john,kan,rocks,rita等...



现在如果我输入字符'K','A ','N'然后单元格将专注于kan。



我有谷歌这个,但我得到解决方案,如下面的代码,不满足我的问题。



因为它是焦点单元格,其中包含按下的字符作为单元格值的起始字符。



提前感谢。



我的尝试:



I want to focus on cell which contains pressed characters.

Assume datagridview which contains two column Name and Address.
Now in Name column there is lot of records Like Nims, john, kan, rocks, rita, etc...

Now if I am entering character 'K','A','N' then cell will be focus on kan.

I have google for this but I get solution as below code which didn't satisfied my question.

Because it is focus cell which contains pressed character as starting character of cell value.

Thanks in advance.

What I have tried:

private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (Char.IsLetter(e.KeyChar))
    {
        for (int i = 0; i < (dataGridView1.Rows.Count); i++)
        {
            if (dataGridView1.Rows[i].Cells["Name"].Value.ToString().StartsWith(e.KeyChar.ToString(), true, CultureInfo.InvariantCulture))
            {
                dataGridView1.Rows[i].Cells[0].Selected = true;
                return; // stop looping
            }
        }
    }
}

推荐答案

你可以定义一个公共变量来保存键入的字符,并在 dataGridView1_KeyPress()中使用它。对于 KeyCodes 请参阅:密钥枚举(System.Windows.Forms) [ ^ ]

You can define a public variable to hold the typed characters and use that in your dataGridView1_KeyPress(). For KeyCodes see: Keys Enumeration (System.Windows.Forms)[^]
public string typedChars = string.Empty;

private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
    if(e.KeyCode == Keys.Left || e.KeyCode == Keys.Right || e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
    {
        typedChars = string.Empty;
        return;
    }

    if (Char.IsLetter(e.KeyChar))
    {
        typedChars += e.KeyChar.ToString();

        for (int i = 0; i < (dataGridView1.Rows.Count); i++)
        {
            if (dataGridView1.Rows[i].Cells["Name"].Value.ToString().StartsWith(typedChars, true, CultureInfo.InvariantCulture))
            {
                dataGridView1.Rows[i].Cells[0].Selected = true;
                return; // stop looping
            }
        }
    }
}


另一种选择是使用 LINQ 通配符搜索,这是一个例子:

C# - 使用LINQ进行通配符搜索 [ ^ ]
Another option would be to use LINQ wildcard search, here is an example:
C# - Wildcard Search Using LINQ[^]


这篇关于如何通过在datagridview中键入charachters来关注单元格C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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