Search code examples
c#wpftextboxformat

"Input String is not in Correct Format" withTextbox Selection Changed Event


private void txtdiscount_SelectionChanged(object sender, RoutedEventArgs e)
{
    try
    {
        string dis = txtdiscount.Text.ToString();
        double isid = double.Parse(dis);

        isid = isid + 10;

        MessageBox.Show(isid.ToString());

    }
    catch (Exception exp)
    {
        MessageBox.Show(exp.ToString());
    }
}

I want to take input(double type) in text box txtdiscount and on SelectionChanged event of a textbox, a MessageBox should display the entered value after increment of 10 in its value. But with the above code, i get an exception that:

"Input String was not correct format"

at line:

string dis = txtdiscount.Text.ToString()

What is wrong with this code in textbox SelectionChanged event as the same code works fine when performed in a button click event?

 <TextBox  x:Name="txtdiscount" HorizontalAlignment="Left" Height="33" Margin="831,97,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="154" SelectionChanged="txtdiscount_SelectionChanged"/>

Solution

  • Your problem is that the SelectionChanged event is fired as soon as you click on the TextBox. At this point there is no value inside so double.Parse() gets an empty string as input and throws this exception. It would also throw the exception when you remove the last digit from the TextBox.

    To solve this situation you can check for empty values:

    private void txtdiscount_SelectionChanged(object sender, RoutedEventArgs e)
    {
        try
        {
            if (!string.IsNullOrWhiteSpace(txtdiscount.Text))
            {
    
                string dis = txtdiscount.Text;
                double isid = double.Parse(dis);
    
                isid = isid + 10;
    
                MessageBox.Show(isid.ToString());
            }
    
        }
        catch (Exception exp)
        {
            MessageBox.Show(exp.ToString());
        }
    }
    

    same code works fine when performed in a button click event

    Because you click after you have entered a valid value. This is the difference