TargetInvocationException occurred, but I have absolutely no idea why

Oned Zair picture Oned Zair · Oct 17, 2012 · Viewed 14.8k times · Source

I'm getting this unhandled exception error:

An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll.

Additional information: Exception has been thrown by the target of an invocation.

This is my code in short. It's a calculator of two TextBoxes which should together become a new answer when the user press +, -, /, x button made in WPF.

public partial class MainWindow : Window
{
    public string numberInString
    {
        get { return TextDoos.Text; }
        set { TextDoos.Text = value; }
    }

    public MainWindow()
    {
        if(TextDoos.Text == "")
        {
            if(TextDoos2.Text == "")
            {
                RekenFunctie(TextDoos.Text, TextDoos2.Text);
            }
        }
    }
}

public int RekenFunctie(string numberInString, string numberInString)
{
    int antwoord;
    int getal = Convert.ToInt32(numberInString);
    int getal2 = Convert.ToInt32(numberInString2);

    if (Buttons.IsPressed) // This is the + button, there are also -,x,/ buttons.
    {
       antwoord = getal + getal2;
       return antwoord;
    }
}

I can't see why it isn't working...

Answer

Anton Sizikov picture Anton Sizikov · Oct 17, 2012

You missed the call of InitializeComponent() in MainWindow constructor;

public MainWindow() 
{ 
     InitializeComponent();
     button1.Click += button1_click; //'+' button
}

private void button1_click(object sender, RoutedEventArgs e)
{
    int antwoord;
    int getal = Convert.ToInt32(TextDoos.Text);
    int getal2 = Convert.ToInt32(TextDoos2.Text);

    antwoord = getal + getal2;
    resultTextBox.Text = antwoord ;
}

Anyway your code is strange. RekenFunctie makes some calculation, but you call it from the constructor. So, you run this code only once, but I think your user wants to interact with your calculator.

I think you should read something about Button.Click events.