Hi guys,

I'm running into an issue that's really frustrating me. It's probably the most common newbie oversight, causing me to get the dreaded NullReferenceException. I've encountered it many times before, but this time it's got me stumped.

I'm filling a Datagrid with a table from a database. I'm able to get the data, and I put it into a class, which is then added to a List<T>, with each new object added a new element of the list. Once the list is built, I bind it to the DataGrid as an ItemsSource.. and that's where I encounter my issue. Right at the end, when binding the data to the datagrid, I get the NullReferenceException. The object seems to have defintely been created, and filled, so nothing should be null at all. Although perhaps I'm missing something? I'd greatly appreciate it if someone could point out where I've gone wrong. Here is a code excerpt:

private void btnForSale_Click(object sender, RoutedEventArgs e)
        {
            List<string> listProperties = new List<string>();
            listProperties = searchPropertiesHandler.GeneratePropertyList();
            List<HandlerSearchProperties.SearchResult> results = new List<HandlerSearchProperties.SearchResult>();
            //results.Add(new HandlerSearchProperties.SearchResult(0, "LOCATION!", "PRICE", "TYPE", "BEDS", "BATHROOMS", "NOTES"));
            //results.Add(new HandlerSearchProperties.SearchResult(0, "-", "-", "-", "-", "-", "-"));
            for (int x = 0; x < listProperties.Count - 6; x += 7)
            {
                results.Add(new HandlerSearchProperties.SearchResult(Convert.ToInt32(listProperties[x]), listProperties[x+1], listProperties[x+2], listProperties[x+3], listProperties[x+4], listProperties[x+5], listProperties[x+6]));
            }
            DataGrid dgResults = new DataGrid();
            dgResults = sender as DataGrid;
            dgResults.ItemsSource = results;
        }

I've also uploaded my solution file. Feel free to download and take a look. When you compile it, if you hit the bottom option (Search Properties), then hit (Search Properties for Sale), you'll see the exception.

https://www.dropbox.com/s/agfjx9s2ok50uuw/ManageUsers.zip

Any guidance on this would be greatly appreciated!

Thanks!

Dani AI

Generated

The NullReferenceException is happening because the Click event’s sender is the Button that was clicked, not the DataGrid. As pointed out, casting the sender to a DataGrid will return Nothing and then calling ItemsSource on that value throws. Also avoid creating a brand‑new DataGrid instance inside the handler — that creates a control that isn’t the one in the window, so setting its ItemsSource has no visible effect. and were right to suggest binding the datasource directly or working with the actual grid instead of trying to use the event sender as the target.

Quick fixes you can apply immediately:

  • Give the UI DataGrid a name in XAML and set its ItemsSource from code-behind (VB.NET example):
    
    ' XAML: <DataGrid x:Name="dgResults" ... />

' Code-behind (VB.NET)
Dim results As New List(Of HandlerSearchProperties.SearchResult)()
' populate results...
dgResults.ItemsSource = results


- If you must use the sender (not recommended here), guard the cast:

Dim dg = TryCast(sender, DataGrid)
If dg IsNot Nothing Then
dg.ItemsSource = results
Else
' fallback: find the named grid in the window
Dim named = TryCast(Me.FindName("dgResults"), DataGrid)
If named IsNot Nothing Then named.ItemsSource = results
End If


Better long-term: adopt binding/MVVM. Expose an ObservableCollection(Of SearchResult) on the ViewModel and bind the DataGrid’s ItemsSource to it; adding/removing items updates the UI automatically:

' ViewModel
Public ReadOnly Property Results As New ObservableCollection(Of SearchResult)()

' XAML
' <DataGrid ItemsSource="{Binding Results}" />



Troubleshooting tips: set a breakpoint and inspect sender.GetType(), use the Live Visual Tree to confirm control names and event wiring, and if you populate data from a background thread marshal to the UI thread (Dispatcher.Invoke). These checks will quickly show whether you are operating on the real DataGrid or on a null/new instance.

Recommended Answers

All 3 Replies

It appears to me that sender is of type Button and you're trying to cast it as a DataGrid. When the cast fails, dgResults will be nothing and any calls to it will result in the exception.

passing the event object sender as datasource of gridview will return empty or exception..!!instead can try this as cretaing a gridview dg and bind the value of result to it..hope this helps you..

When you have the values of a table from the database, why dont you bind that to the gridview directly ?
that should help you reduce your code as well.
Bind the Datasource of the grid view.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.