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