Siegfried XVI
Siegfried XVI

Reputation: 45

Why do I get a System.InvalidOperationException?

I'm really desperate at the moment. I'm programming a WPF-programm. I built a simple XAML-construct and generated grids and within the grids labels dynamically, based on how many elements are stored in the database. Even though I defined the Label and named it label, I get an System.InvalidOperationException. I found this solution here. My actual problem was, that I needed to get the content of the label in this grid. I made all similar to the question, which I linked.

I hope that you understand what I mean.

Here my code:

for (int i = 0; i < numberOfBooks; i++)
{
    Grid grid = new Grid();
    RowDefinition row = new RowDefinition();

    ColumnDefinition column = new ColumnDefinition();
    ColumnDefinition column2 = new ColumnDefinition();
    ColumnDefinition column3 = new ColumnDefinition();

    Label label = new Label();
    label.Content = Books[i].Titel;

    upperGrid.RowDefinitions.Add(row);
    grid.ColumnDefinitions.Add(column);
    grid.ColumnDefinitions.Add(column2);
    grid.ColumnDefinitions.Add(column3);

    Grid.SetRow(label, i);
    Grid.SetColumn(label, 0);
    Grid.SetRow(grid, i);
    upperGrid.Children.Add(grid);
    grid.Children.Add(label);

    grid.MouseLeftButtonDown += (sen, evg) =>
    {
        Label lbl = grid.Children.OfType<Label>().First(k => k.Name=="label"); //Here I get the exception
        string result = lbl.Name.ToString();
        Console.WriteLine(result);
    }; 
}

Upvotes: 2

Views: 478

Answers (1)

Salah Akbari
Salah Akbari

Reputation: 39966

First will throw. Use FirstOrDefault that will return the default<T> and also null-conditional operator (?.):

Label lbl = grid.Children.OfType<Label>().FirstOrDefault(k => k.Name=="label");
string result = lbl?.Name.ToString();
Console.WriteLine(result);

However, Since this is a WPF project, I suggest use a MessageBox or something similar to show the result, instead of Console.WriteLine, like this:

Add this to your using directives first:

using System.Windows; 

And then:

MessageBox.Show(result);

Upvotes: 2

Related Questions