Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# How to enforce uppercase in a specified colum of a DataGridView?

I would like to be able to set the CharacterCasing of a specified column to uppercase.

I can't find a solution anywhere that will convert characters to uppercase as they are typed.

Many thanks for any help

like image 703
mat b Avatar asked Dec 22 '22 01:12

mat b


1 Answers

You need to use EditingControlShowing event of the Datagridview to edit the contents of any cell in a column. Using this event you can fire the keypress event in a particular cell. In the keypress event you can enforce a rule which will automatically convert lowercase letters to uppercase.

Here are the steps to achieve this:

In the EditingControlShowing event see whether user is in the column in which you want to enforce this rule. Say your column is 2nd column in the grid

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
}

If you want to set the CharacterCasing property of the textbox control in the column, then you can do it where KeyPress event registering is done in the above code, which is in the 'if' block of checking column index. In this case you can avoid KeyPress event.

That can be done in the following way:

if(e.Control is TextBox)
{
  ((TextBox) (e.Control)).CharacterCasing = CharacterCasing.Upper;
}
like image 200
JPReddy Avatar answered Dec 31 '22 12:12

JPReddy