Reputation: 630
I have a datagrid that's populated by a MySQL table. The issue here is I've added to it a SelectionChanged event.
private void RegistrationDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// if the datagrid has an index value of 0 and above
if (RegistrationDataGrid.SelectedIndex >= 0)
{
// Exception gets thrown here
DataRowView row = (DataRowView)RegistrationDataGrid.SelectedItems[0];
// if the column Tag of the selected row in the datagrid is not empty
if (row["Tag"] != null)
{
//put the content of the cell into a textbox called tag
tag.Text = Convert.ToString(row["Tag"]);
}
}
}
The above code is meant to capture the value of a cell in a specific column of the selected row. This works fine.
The problem arises if you select the last row, the one that's always there. The empty one at the bottom with nothing inside it.
An Invalid cast Exception gets thrown: "Unable to cast object of type 'MS.Internal.NamedObject' to type 'System.Data.DataRowView"
My assumption is that it's got to do with the fact that the selected row is empty. I just need to find a way to get the event to ignore this row when ever it's selected. Any clues?
Upvotes: 2
Views: 5063
Reputation: 7918
You should use String.IsNullOrEmpty()
function to validate the content of that cell, prior to any use of it. Also, before that add another validation to make sure that row!=null
and castedRow!=null
.
Regarding your description of "empty last row" - this might be an "add new row" template: check for the DataGridView.AllowUserToAddRows
property (set it to false if you don't use it, so that last "empty row" will disappear).
The final code with Exception handling may look like the follows:
private void RegistrationDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataRowView _drv;
try
{
_drv = RegistrationDataGrid.SelectedItems[0] as DataRowView;
if (_drv != null && _drv ["Tag"] != null && !String.IsNullOrEmpty(Convert.ToString(_drv ["Tag"]) )
{
tag.Text = Convert.ToString(_drv["Tag"]);
}
else{tag.Text=String.Empty;}
}
catch{tag.Text=String.Empty;}
finally{_drv=null;}
}
Hope this will help. Regards,
Upvotes: 2
Reputation: 5894
Avoid explicit casting if you're not sure wether it will actually perform successfully. I'd have used this:
var row = RegistrationDataGrid.SelectedItems[0];
DataRowView castedRow = RegistrationDataGrid.SelectedItems[0] as DataRowView;
if (castedRow != null && castedRow ["Tag"] != null) <------ DONT skip on checking castedRow for null, jumping directly to indexed access.
{
//put the content of the cell into a textbox called tag
tag.Text = Convert.ToString(castedRow["Tag"]);
}
Upvotes: 3