All capitals by Key Press

  • Thread starter Thread starter Manu Singhal
  • Start date Start date
M

Manu Singhal

Hi


I am trying to build a windows forms control which derieves from TextBox.
The added functionality that i want is that

I want every character that appears on the TextBox should be in Capitals.


For this i have created a Class iTextBox and Derieved from TextBox and have
overriden the OnKeyPress Method Here is the code :-

protected override void OnKeyPress(KeyPressEventArgs e)

{


if(Char.IsLetter(e.KeyChar))

{

e = new KeyPressEventArgs(Char.ToUpper(e.KeyChar));


}

base.OnKeyPress (e);


}



But when i test the class it the method runs but the characted is not
converted to Upper case.







Please help and advice.





Manu Singhal
 
Hello,
You can do it with another approach.

<code lang='C#'>
protected override OnKeyPress(KeyPressEventArgs e)
{
if(Char.IsLetter(e.KeyChar) && Char.IsLower(e.KeyChar))
{
this.Text += Char.ToUpper(e.KeyChar);
this.SelectionStart = this.Text.Length;
e.Handled = true;
}
else
base.OnKeyPress(e);
}
</code>

Don't make an inherited textbox if you are doing it only for this
purpose, it can be achieved via KeyPressed event. You will only need to
ignore the 'else' part from the code in that case.

HTH. Cheers.
Maqsood Ahmed [MCP C#,SQL Server]
Kolachi Advanced Technologies
http://www.kolachi.net
 
Manu,

You can use the CharacterCasing property of the TextBox for that:

textBox1.CharacterCasing = CharacterCasing.Upper

The version you have writtten only seems to lack the assignment:

e.Handled = true;

in the event handler.

Regards - Octavio
 
Manu,

An even easier option is to go to the Properties window while your text
box is still selected and go down to Behaviour, and change the
CharacterCasing from Normal to Upper,

Visually Seen #
 
Back
Top