c#如何在DataGridView的指定列中强制使用大写?

mat*_*t b 4 c# datagridview winforms

我希望能够将指定列的CharacterCasing设置为大写.

我找不到任何可以在键入字符时将字符转换为大写的解决方案.

非常感谢任何帮助

JPR*_*ddy 8

您需要使用Datagridview的EditingControlShowing事件来编辑列中任何单元格的内容.使用此事件,您可以触发特定单元格中的按键事件.在按键事件中,您可以强制执行一条规则,该规则会自动将小写字母转换为大写.

以下是实现此目的的步骤:

在EditingControlShowing事件中,查看用户是否在要强制执行此规则的列中.假设您的列是网格中的第二列

private void TestDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if(TestDataGridView.CurrentCell.ColumnIndex.Equals(1))
    {
        e.Control.KeyPress += Control_KeyPress; // Depending on your requirement you can register any key event for this.
    }
}

private static void Control_KeyPress(object sender, KeyPressEventArgs e)
{
    // Write your logic to convert the letter to uppercase
}
Run Code Online (Sandbox Code Playgroud)

如果要在列中设置CharacterCasing文本框控件的属性,则可以KeyPress在上述代码中完成事件注册,该代码位于检查列索引的"if"块中.在这种情况下,您可以避免KeyPress事件.

这可以通过以下方式完成:

if(e.Control is TextBox)
{
  ((TextBox) (e.Control)).CharacterCasing = CharacterCasing.Upper;
}
Run Code Online (Sandbox Code Playgroud)