How to convert TextBox input to Upper Case?

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
 
S

Stuart Celarier

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top