Hi
i received from someone of your experts this code in order to accept both integer and double in the same textbox.
The problem is that when entering a double (5,2), i get an error "The format of the input string is incorrect." at line int valueInt = Int32.Parse(textboxValue);. The inversre is ok: when entering a integer, there is no error.
How to avoid this?
Thanks
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// Verify that the pressed key isn't CTRL or any non-numeric digit
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != ','))
{
e.Handled = true;
}
// If you want, you can allow decimal (float) numbers
if (e.KeyChar == ',' && (sender as TextBox).Text.IndexOf(',') > -1)
{
e.Handled = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
string textboxValue = textBox1.Text;
// Retrieve as decimal
decimal valueDec = decimal.Parse(textboxValue);
label1.Text = valueDec.ToString();
// Retrieve as integer
int valueInt = Int32.Parse(textboxValue);// error
label2.Text = valueInt.ToString();
}
Sachin SinghPosted Jan 31, 2022, 3:06 PM
Valerie MeunierPosted Jan 31, 2022, 2:26 PM
Sachin SinghPosted Jan 31, 2022, 12:13 PM
Valerie MeunierPosted Jan 31, 2022, 11:53 AM
Sachin SinghPosted Jan 31, 2022, 10:16 AM
Is it necessary for you? can't you set your PC to consider (dot) as dot and not comma(,) ??
here how you can do it.
Settings/time&language/under related settings click “Additional date, time, & regional settings”/under region click “change date, time, or number formats/a dialog box pops up, click additional settings/numbers tab, decimal symbol - change to .
Apply, ok,
then apply, ok
Valerie MeunierPosted Jan 31, 2022, 10:04 AM
Muhammad Imran AnsariPosted Jan 31, 2022, 9:54 AM
First remove comma (5,2) from your value and you can also use Math.Truncate() method to get only integral part of any fractional digits.
int valueInt = (int)Math.Truncate(Convert.ToDecimal(textboxValue));
Sachin SinghPosted Jan 31, 2022, 9:22 AM
Amit MohantyPosted Jan 31, 2022, 9:01 AM
Hey did you check you are getting correct value when you convert textbox value to decimal. Please check once again, i think you are not getting the right value.
Please check with below code. May be this what you want.