I have a Silverlight DataGrid, not an asp Gridview, that gets populated just fine. I have added a checkbox column for the user to select which items they want to download. My goal is to create a ‘cart’ where the user can select their items, then click a button to add them. Then they will go to a checkout page etc..
My problem so far is that I am having trouble checking to see if the user checked a check box or not. My foreach loops through fine I think, but I get a ‘nullreferenceexception’ in the bool IsChecked line. During a breakpoint, none of the values came back as null that I saw but it obviously isnt working the way I hoped.
foreach (var row in gridResults.ItemsSource)
{
bool IsChecked = (bool)((CheckBox)gridResults.Columns[8].GetCellContent(row)).IsChecked;
if (IsChecked)
{
List<string> lstFile = new List<string>();
string fileName = (gridResults.SelectedItem as JobSearchResult).FileName;
lstFile.Add(fileName);
}
}
Through the filename, I can find the files on the server for them to download, but How can i check if they checked the ones they wanted or not?
Without knowing precisely how you are populating your datagrid, it is difficult to tell you what the exact cause of your issue is. But I will tell you how I would handle this situation.
Create an ObservableCollection of your object type. Set the ItemsSource of the DataGrid to the ObservableCollection. Then, in the data grid row, create a binding for the IsChecked property of the checkbox to some public boolean value on your object (perhaps call that IsSelected). Make sure to set the binding mode to TwoWay.
Then, all you have to do is use a linq query on the ObservableCollection. Remember that Silverlight is a presentation layer, and you should not rely upon it at all to perform business logic.