Dear all,
I just recently start to learn programming in C#.
I would like to have an exeption if the characters I put in 2 seperate textboxes are numbers.
e.g.:
tb_Value 1: "First Value"
tb_Value 2: "Second Value"
btn_Button:
--> tb_Result: "First Value" + " " + "Second Value"
I can display it and all that, but I want to display a message (exception catch) if in one of these two textboxes, when one one of the two values contains other characters than normal letters. I would also like to display a message (exception catch) if the first character of one of these values is not an uppercase.
The intension of it all is to be able to fill in the first name in a textbox, the second name in a textbox, and unify these two in a third textbox with a space in between.
Can someone give me some advise regarding this "problem"?
Thanks in advance!
Kevin.
Loading
JurePosted Nov 3, 2010, 10:48 AM
I hope you get the idea.
Kevin BrigittaPosted Nov 3, 2010, 10:16 AM
The thing is, I don't really want to remove an invalid character, but given an exception error message.
If in the tb_Value1 is typed: "45312"
--> exception message: "this is not a valid value"
If in the tb_Value1 is typed: "kevin"
--> exception message: "the first letter is not an uppercase"
It actually concerns try - catch exceptions with a messagebox showing if the entered value throws an exception.
But thanks anyway!
JurePosted Nov 3, 2010, 9:54 AM
int prev_lenght = 1;
textBox.TextChanged += (object o, EventArgs e) =>
{
try
{
if (textBox.Text[0] < 'A' || textBox.Text[0] > 'Z')
{
textBox.Text = "";
}
}
catch (IndexOutOfRangeException) {
prev_lenght = 1;
return;
}
for (int i = prev_lenght; i < textBox.Text.Length; ++i)
{
if (textBox.Text[i] < 'a' || textBox.Text[i] > 'z')
{
textBox.Text = textBox.Text.Remove(i);
textBox.SelectionStart = i;
prev_lenght = textBox.Text.Length;
break;
}
}
};
The reason for prev_lenght is that your program doesn't check whole text each time, but just the part that was added, which is more efficient. User could type manually char by char or he/she could copy a string of characters into your textbox, and the program should know how much was added in a single "TextChange".
It's not very user friendly though. I suggest you to simply disable the button and display a message next to the texbox about invalid formatting.
So if you'd rather do that, then just copy the above code as it is, but change the actions (i.e. button.Enabled = false instead of removing invalid characters).