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
C#
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 SinghRank #66 · 26.2K reputationPosted Jan 31, 2022, 4:22 AM EST
Amit MohantyRank #112 · 20K reputationPosted Jan 31, 2022, 4:01 AM EST
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.
Muhammad Imran AnsariRank #326 · 7.6K reputationPosted Jan 31, 2022, 4:54 AM EST
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));
Valerie MeunierRank #1,527 · 1K reputationPosted Jan 31, 2022, 5:04 AM EST
Sachin SinghRank #66 · 26.2K reputationPosted Jan 31, 2022, 5:16 AM EST
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 MeunierRank #1,527 · 1K reputationPosted Jan 31, 2022, 6:53 AM EST
Sachin SinghRank #66 · 26.2K reputationPosted Jan 31, 2022, 7:13 AM EST
Valerie MeunierRank #1,527 · 1K reputationPosted Jan 31, 2022, 9:26 AM EST
Sachin SinghRank #66 · 26.2K reputationPosted Jan 31, 2022, 10:06 AM EST