How to convert TextBox input to Upper Case?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi, All
Is it possible to convert input in the TextBox to Upper case, something
similare like in VB.6
Private Sub TextBox1_KeyPress(KeyAscii as Integer)
KeyAscii = Asc(UCase(Chr(KeyAscii)))
End sub
I need to display all input in Upper Case for the user during the typing
process.
Please, advice

elena
 
I tracked down Daniel's references and this seems to be the best method:

using System.Windows.Forms;

public class UpperCaseTextBox : TextBox
{
protected override void OnKeyPress( KeyPressEventArgs e )
{
if ( char.IsLower( e.KeyChar ) )
{
int start = SelectionStart;
Text = Text.Insert( start, char.ToUpper( e.KeyChar ).ToString() );
SelectionStart = start + 1;
e.Handled = true;
}
else
base.OnKeyPress( e );
}
}

This approach is more efficient than another popular solution which
overrides the OnTextChanged method and converts the entire Text string
to uppercase each time it is changed.

Use UpperCaseTextBox as you would a TextBox. For example:

using System.Drawing;
using System.Windows.Forms;

public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox textBox;

public Form1()
{
textBox = new UpperCaseTextBox();
textBox.Location = new Point( 10, 10 );
Controls.Add( textBox );
Text = "Form1";
}

static void Main()
{
Application.Run( new Form1() );
}
}

Cheers,
Stuart Celarier, Fern Creek
 
Back
Top