2

Here's my code:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        //myOnlyGrid = new Grid();
        Chart MyChart = new Chart();
        ColumnSeries b = new ColumnSeries();

        b.Title = "B";

        b.IndependentValueBinding = new System.Windows.Data.Binding("Key");
        b.DependentValueBinding = new System.Windows.Data.Binding("Value");

        b.ItemsSource = new List<KeyValuePair<string, int>> {
                new KeyValuePair<string, int>("1", 100),
                new KeyValuePair<string, int>("2", 75),
                new KeyValuePair<string, int>("3", 150)
            };


        MyChart.Series.Add(b);

        Grid.SetColumn(MyChart, 0);

        Thread.Sleep(1000);
        myOnlyGrid.Children.Add(MyChart);

        InitializeComponent();
    }

and my XAML:

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid Name="myOnlyGrid">

</Grid>

For some reason, it compiles fine but throws a nullreferenceexception whenever it reaches myOnlyGrid.Children.Add(). I've been googling for about an hour and haven't found anything.

3 Answers 3

4

Put

myOnlyGrid.Children.Add(MyChart);

after InitializeComponent()

myOnlyGrid gets created and initialized only in InitializeComponent call and before that line it's simply null so you are basically calling null.Children.Add(MyChart) which gives NullReferenceException

Sign up to request clarification or add additional context in comments.

Comments

3

You should call InitializeComponent() on the first line of your constructor.

Also, this isn't a great place to put this type of code. Consider MVVM.

Comments

1

Move all the code after the InitializeComponent() call. When performing the operation before that the instance of the grid hasn't yet been created.

In fact, if you go to definition on that method you'll see that the markup you write is just syntactic sugar for code that is written and executed. And that's been the case forever.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.