Uppercase only textbox?

C

Chris Voon

Wondering anyone has got some information or resource on
any uppercase only textbox that's around?

Regards
Chris Voon
 
M

Maarten Struys, eMVP

What you can do is derive your own "upper case only" textbox from TextBox.
Here is a sample:

public class UCTextBox : TextBox
{
public UCTextBox()
{
}

protected override void OnKeyPress(KeyPressEventArgs e)
{

if(Char.IsLetter(e.KeyChar))
{
// save the current caret position
int pos = this.SelectionStart;

// insert the upper case character
this.Text = this.Text.Insert(this.SelectionStart,
Char.ToUpper(e.KeyChar).ToString());

// and update the current caret position
this.SelectionStart = pos + 1;
e.Handled = true;
}

base.OnKeyPress(e);

}
}
 
S

Shreekanth Gaanji

The above example wroks fine.It needs to handle a couple of other conditions like a mentioned below.

1. The code will not account the case where there are characters selected (highlighted), and therefore it appends to the value instead of replacing those that are highlighted.
For example having: ABCDE in a field and typing X, should render: ABXE, instead it renders ABXCDE
2.Another issue is that, Even though if i set MaxLength property to some fixed value but it will not restrict the user.

I have modified the code as below. It is working fine now.

public class myTextBox : TextBox
{
public myTextBox ()
{
InitializeComponent();
}

protected override void OnKeyPress(KeyPressEventArgs e)
{
int start = SelectionStart;
if (SelectionLength > 0)
SelectedText = string.Empty;

if (Text.Length == MaxLength)
{
e.Handled = true;
}
else
{
if (char.IsLower(e.KeyChar))
{
Text = Text.Insert(start, char.ToUpper(e.KeyChar).ToString());
SelectionStart = start + 1;
e.Handled = true;
}
base.OnKeyPress(e);
}
}
}
 

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