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!

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.

Edited 2 Years Ago by tinstaafl

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.

This article has been dead for over six months. Start a new discussion instead.