开发者

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.

开发者_如何学JAVA

Many thanks for any help


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


Currently i really know, but if you could get access to the editing control of the column (which is a TextBox) you could probably set the CharacterCasing property.


Use EditingControlShowing event of the Datagridview to Edit the contents

After that Apply the Condition For Specific Column

private void dgvGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
      if (dgvGrid.CurrentCell.ColumnIndex == 0 || dgvGrid.CurrentCell.ColumnIndex == 2)
          {
           if (e.Control is TextBox)
              {
                ((TextBox)(e.Control)).CharacterCasing = CharacterCasing.Upper;
              }
          }
    }

Happy Coding

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜