TargetInvocationException occurred, but I have absolutely no idea why

15.1k views Asked by At

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...

2

There are 2 answers

5
Anton Sizikov On BEST ANSWER

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.

0
bnieland On

I was having a similar problem.

I was getting the same error when setting the text on a TextBlock from a property changed evet for a TextBox.

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        MainTextBlock.Text = ((TextBox)sender).Text;
    } 

I think it was being called at runtime before the MainTextBlock component was initialized.

In my case, just checking for null did the trick.

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (MainTextBlock != null)
            MainTextBlock.Text = ((TextBox)sender).Text;
    }