I am currently working on a custom control that allow users to enter either a decimal or in time format (hh:mm). So I would like that if the TextBox contain a period(.), the user will no longer add/enter a colon(:) and vice versa.
I have this code below so that user can only enter numeric, a period and a colon.
private void txtTime_KeyPress(object sender, KeyPressEventArgs e)
{
if ((!char.IsControl(e.KeyChar) & !char.IsDigit(e.KeyChar) & !(Convert.ToString(e.KeyChar) == ".") & !(Convert.ToString(e.KeyChar) == ":")))
{
e.Handled = true;
}
else
{
//only allow one '.' & ':'
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
else if (e.KeyChar == ':' && (sender as TextBox).Text.IndexOf(':') > -1)
{
e.Handled = true;
}
}
}
So my question is, how will I do it?
Can somebody help me? Thanks in advance.
For operators it is a nuisance if they have typed something, and they want to correct it, but they can't because there is an incorrect dot or a semicolon in it.
Suppose the operator tried to type 14:38:21, but instead types:
14.38
"Oh no, this is wrong, I wanted 14.38:21! So let's first continue typing :21 and then go back to change the dot into a colon!"
Imagine the operator's frustration when he can't type :21, and doesn't understand why
In windows forms, only validate entered input when the operator expresses he finished editing the input.
Therefore, use TextBox.OnValidating. When this one is called, you can either accept or decline the input and tell the operator what is wrong.
protected override void OnValidating (CancelEventArgs e)
{
e.Cancel = this.IsInputErrorDetected;
if (e.Cancel)
{
this.DisplayInputProblem();
}
}
Bonus point: also works with copy-paste.
I am not sure, if I understand your question good.
Maybe you are looking for maskedTextBox where you can specify mask of user input.
This one has mask for short time HH:MM
Related
I need some help because I can't seem to get to display the text label here. I am using Windows Form C# VS 2015. When I press enter the error is on barangay = int.Parse(lblDistrict.Text); uhm also, I am applying the same way console.readline is used but it seems that it doesn't work. Can somebody help me in the code? :) Thanks in advance
private void txtBarangay_KeyPress(object sender, KeyPressEventArgs e)
{
int barangay = 0;
barangay = int.Parse(lblDistrict.Text);
if (e.KeyChar == (char)13)
{
if (barangay >= 1 && barangay <= 146)
{
lblDistrict.Text = "District 1";
}
else if (barangay >= 147 && barangay <= 267)
{
lblDistrict.Text = "District 2";
}
}
}
It is the matter of focus. When you press the key, which control is focused? Is it the one that you have written the KeyPress event for?
So you must make sure that either when the key is pressed either that specific control has the focus, or add this even to all controls.
I don't know what kind of Exception you get , but you must use Int.TryParse instead of int.parse .
check this link http://dailydotnettips.com/2016/01/16/back-to-basic-difference-between-int-parse-and-int-tryparse/
Thanks
First, Please include try-catch block in your program in-order to catch the exception.
If the string in the textBox contains anything other than ONLY numbers (Example "12er"), It will throw Exception. Try Int.TryParse if this is the case
I'm currently working on a calculator project and I have run into two problems.
The first problem is how to handle the keypress event so that numbers plus (+-/*.) all work however every other key is blocked. Heres the code im using at the moment:
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
I know I could add each symbol separately by using && (e.KeyChar != '+') && (e.KeyChar != '-') but is there an easier more efficient way of handle all of these keys?
Edit: Sorry forgot to mention that my calculator uses a text box so that is why I need to block the use of letters and some symbols
My second question is how can I stop the user being able to write two or more decimal points in one number for example 9.5.6 or 0.3.2.9?
Thanks
Declare char array on class level:
private char[] allowed = new char[]
{
'/','*','+','-'
};
On keypress event:
if (!char.IsDigit(e.KeyChar) && !allowed.Contains(e.KeyChar) )
{
e.Handled = true;
}
I have a simple form that takes 9 decimal numbers from 9 textboxes and I put some validation so that the users can only enter decimal numbers and nothing else.
Now the challenge I'm having is how to set the cursor in the textbox that had no decimal number after showing the error message in the try-catch statement?
Here's my code:
private void btn_Aceptar_Click(object sender, EventArgs e)
{
POI GPI = new POI();
POI VIM = new POI();
POI ST = new POI();
try
{
GPI.POI_x = Convert.ToDecimal(txt_GPIx.Text);
GPI.POI_y = Convert.ToDecimal(txt_GPIy.Text);
GPI.POI_z = Convert.ToDecimal(txt_GPIz.Text);
VIM.POI_x = Convert.ToDecimal(txt_VIMx.Text);
VIM.POI_y = Convert.ToDecimal(txt_VIMy.Text);
VIM.POI_z = Convert.ToDecimal(txt_VIMz.Text);
ST.POI_x = Convert.ToDecimal(txt_STx.Text);
ST.POI_y = Convert.ToDecimal(txt_STy.Text);
ST.POI_z = Convert.ToDecimal(txt_STz.Text);
}
catch (Exception)
{
MessageBox.Show("Ingrese solamente nĂºmeros en las variables GPI/VIM/ST", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
//Set the cursor in the first textbox that had no decimals..
return;
}
Comisurales Comisurales = new Comisurales();
Comisurales.calculo_coord_comisurales(PC, AC, IHP, GPI, VIM, ST);
}
Let me add that I also have a function to ensure the user is only limited to enter decimals but I wasn't able to figure how to avoid the "." only or this for example: "1."
As an addition to my question, here's what gets validated every time the user press a key in the textbox:
private void ValidarDecimal(object sender, KeyPressEventArgs e)
{
// permitir 0-9, backspace, y decimal
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
{
e.Handled = true;
return;
}
// chequear solamente un decimal
if (e.KeyChar == 46)
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
}
I guess I have 2 ways to resolve my issue. Number one would be find a way to ensure the user never ever enters something weird in the textbox (which I've done partially) and number 2 would be to use the try-catch with the current limitations I mentioned above and then point the user to the textbox that has issues, both are acceptable.
The Decimal class has a TryParse method that could be used to avoid all this logic driven by catching exceptions (a very expensive approach in terms of performance)
decimal value;
if(decimal.TryParse(txt_GPIx.Text, out value))
GPI.POI_x = value;
else
{
MessageBox.Show("Invalid decimal value");
txt_GPIx.Focus();
}
Of course this code needs to be repeated for every control in your list, but you could write a generic function like this one
private decimal GetValueAndValidate(Textbox txt, out bool isOK)
{
isOK = true;
decimal value = 0m;
if(!decimal.TryParse(txt.Text, out value))
{
MessageBox.Show("Invalid decimal value");
txt.Focus();
isOK = false;
}
return value;
}
and then use the following approach in your code inside the button click
bool isOK = true;
if(isOK) GPI.POI_x = GetValueAndValidate(txt_GPIx, out isOK);
if(isOK) GPI.POI_y = GetValueAndValidate(txt_GPIy, out isOK);
.... and so on for the other fields ....
For the second part of your question, finding a way to completely control the input logic is not easy. What happens for example if your user PASTE an invalid text in your textbox? There are very edge case situations that takes a lot of effort to code correctly. It is a lot more easy to leave freedom of typing to your user and apply a strict logic when you get that input.
I have written a little program. It works almost as I want, I just have one problem. I am trying to copy all functions I have found in the other program.
I have a TextBox, when the user can write a phone number. Firstly, he is only allowed to use digits and "+"and "-", so I use:
private void textBoxPhoneNumber_KeyPress(object sender, KeyPressEventArgs e)
{
if ((char.IsDigit(e.KeyChar) == false) && (e.KeyChar != '+') && (e.KeyChar != '-') && (e.KeyChar != '\b')) e.Handled = true;
}
Then I want the phone number to be in certain format (+12-34-1234567), so I use:
private bool IsPhoneNumberCorrect(string name)
{
return Regex.IsMatch(name, #"^+\+[0-9]{2}-[0-9]{2}-[0-9]{7}$", RegexOptions.None);
}
and finally this (with TextChange):
private void phoneNumberValidity(object sender, EventArgs e)
{
counter4 = Convert.ToInt32(IsPhoneNumberCorrect(textBoxPhoneNumber.Text));
pictureBoxPhoneNumber.Image = imageList1.Images[counter4];
checkIfOk();
textBoxPhoneNumber.Focus();
}
I use counter4 as a part of method (checkIfOk) that enables button. There is also an "X" icon that changes into "tick" when the number is given in proper format.
It works perfectly for me (just like in the program I am copying) - when the user writes something in the TextBox, he can only use digits and "+" and "-" and when the format is ok the icon changes and when other textboxes are also ok, the Ok buton enables.
Now, finally, the problem:
I am able to paste something from the Clipboard. In the original program, when I paste something with letters, digits and other signs, only digits and "+" and "-" remains. My program accepts everything in such situation.
I've been looking for something that might be helpful, but all I have found was very complicated. Is there a way to do it?
I tried to do something like this. It causes that when pasting only digits and "+" and "-" remains as it should, but the user can't write anything.
I am still a beginner. Maybe I am making a simple mistake?
private void phoneNumberValidity(object sender, EventArgs e)
{
Regex regex = new Regex("[^0-9-+]");
if (regex.IsMatch(Clipboard.GetText()))
{
counter4 = Convert.ToInt32(IsPhoneNumberCorrect(textBoxPhoneNumber.Text));
pictureBoxPhoneNumber.Image = imageList1.Images[counter4];
string output = regex.Replace(Clipboard.GetText(), "");
textBoxPhoneNumber.Text = output;
checkIfOk();
textBoxPhoneNumber.Focus();
}
}
I am trying to do something like this:
private void phoneNumberValidity(object sender, EventArgs e)
{
counter4 = Convert.ToInt32(IsPhoneNumberCorrect(textBoxPhoneNumber.Text));
pictureBoxPhoneNumber.Image = imageList1.Images[counter4];
checkIfOk();
textBoxPhoneNumber.Focus();
Regex regex = new Regex("[^0-9-+]");
if (textBoxPhoneNumber.Text.Contains("a"))
{
if (regex.IsMatch(Clipboard.GetText()))
{
string output = regex.Replace(Clipboard.GetText(), "");
textBoxPhoneNumber.Text = output;
}
}
}
I know that it's not exactly what I want, but maybe someone can give some clues...
Generally i thought, that I'd like to check if the text in tb contains some unwanted elements, but I don't know how to check it. As you can see, it checks only one unwanted element.
First of all, please use TRY-Catch for the Convert.ToInt32 !
Second: Use TextChanged event, and validate the input with the actual content of the TextBox
To validate, you can do something similar:
string output = ""
string clipboardText = GetClipboardText()
for each chara in clipboardText's characters
if chara.isNumeric or chara=='+' or chara == '-'
output += chara
end foreach
Of course its just a simple soultion, but you can confgure it as you want.
Or if you want more complex way, you can play with the regex... Start with number or + - BUT not contains alphabetical char. Based on your request.
This is what I made, and it works :) I will only add try-catch block as Krekkon has suggested.
private void phoneNumberValidity(object sender, EventArgs e)
{
counter4 = Convert.ToInt32(IsPhoneNumberCorrect(textBoxPhoneNumber.Text));
pictureBoxPhoneNumber.Image = imageList1.Images[counter4];
if (Regex.IsMatch(textBoxPhoneNumber.Text, "[^0-9-+]"))
{
Regex regex = new Regex("[^0-9-+]");
string output = regex.Replace(Clipboard.GetText(), "");
textBoxPhoneNumber.Text = output;
}
checkIfOk();
textBoxPhoneNumber.Focus();
}
Maybe it will help someone in the future.
Maybe you should try like this: leave the first version of phoneNumberValidity method as it is and then check if the tb Text has some unwanted elements, get rid of them.
Hello Fellow C# and Windows phone developers,
For my windows phone application, I have a textfield requiring the user to enter their age. During debugging mode I entered the number .8. and clicked proceed and the application unexpectedly closed. What code do I need to add so I can post a message box informing the user that numbers with more than 1 decimal point is unacceptable. Please Help
Assuming the input is a string, try:
if (input.IndexOf('.') == -1 || input.LastIndexOf('.') == input.IndexOf('.'))
{
//good
}
else
MessageBox.Show("More than one decimal point");
A better way though would be to use TryParse which will check the number for formatting
float age;
if (float.TryParse(input, out age))
{
//good
}
else
MessageBox.Show("Invalid age.");
one way would be to limit the number of decimal place input to just one decimal place when user is entering their input.
this would be much better as it is real time instead of checking it at the end.
private void tbx_KeyDown(object sender, KeyEventArgs e)
{
//mark the sneder as a textbox control so we can access its properties
TextBox textBoxControl = (TextBox)sender;
//if there is already a decimals, do not allow another
if (textBoxControl.Text.Contains(".") && e.PlatformKeyCode == 190)
{
e.Handled = true;
}
}