Valerie Meunier

Valerie Meunier

  • NA
  • 693
  • 84.1k

The format of the input string is incorrect.

Jan 31 2022 8:27 AM

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

Answers (9)