WilliamV WilliamV - 1 month ago 5
C# Question

Implement function in click event

So i have created a function ParseandWarn to pop up a message box if the input is not an integer. If it is an integer, the sum of both inputs must be calculated on the click event. There are multiple calculations, that is why i created the function. How do I implement/activate this function in the click event? I am getting an error, probably the parsing?
I am new to programming, any help is welcome.

public void ParseandWarn()
{
int Invoergetal1, Invoergetal2;
if (!int.TryParse(txtGetal1.Text, out Invoergetal1))
{
MessageBox.Show("U dient een geheel getal in te voeren!", "Fout", MessageBoxButton.OK, MessageBoxImage.Error);
}
else
{
if (!int.TryParse(txtGetal2.Text, out Invoergetal2))
{
MessageBox.Show("U dient een geheel getal in te voeren!", "Fout", MessageBoxButton.OK, MessageBoxImage.Error);
}
else
{
return;
}
}
}

private void btnSom_Click(object sender, RoutedEventArgs e)
{
int BerekenSom = int.Parse(txtGetal1.Text) + int.Parse(txtGetal2.Text);
txtResultaat.Text += "De som van " + txtGetal1.Text + " en " + txtGetal2.Text + " = " + BerekenSom + Environment.NewLine;

}

Answer

This will be the code that you are looking for.

I have used the ref as reference in the function ParseandWarn, that indicates that the parameters will be modified by reference.

public bool ParseandWarn(ref int Invoergetal1, ref int Invoergetal2){
    bool valid = false;
    if ((!int.TryParse(txtGetal1.Text, out Invoergetal1) || !int.TryParse(txtGetal2.Text, out Invoergetal2)) {
        MessageBox.Show("U dient een geheel getal in te voeren!", "Fout", MessageBoxButton.OK, MessageBoxImage.Error);
        return false;
    }
    return true;   
}

private void btnSom_Click(object sender, RoutedEventArgs e)
{
    int Invoergetal1, Invoergetal2;
    bool correctInput = ParseAndWarn(ref Invoergetal1, ref Invoergetal2);
    if(correctInput)
    {
       int BerekenSom = Invoergetal1 + Invoergetal2;
       txtResultaat.Text += "De som van " + txtGetal1.Text + " en " + txtGetal2.Text + " = " + BerekenSom + Environment.NewLine;
    }
}

We pass in two ints into the function, gets a result of the TryParse method, if it fails, they will contain zero instead.

Now, the event handler will have the values, and by computing the sum of the two variables the result will be obtained.

Edit Extra checks for invalid inputs, or null is left as an exercise.

Comments