Friday, November 15, 2013

DataGridview current row returns null in SelectionChanged Event

When retrieving selected row cell values in the DataGridview, you might encounter object not set to reference of an instance. It's because the current row has not been initialized. Check first the cell value of the current row if it has cell contents.
Code:
private void dgvAccounts_SelectionChanged(object sender, EventArgs e)  
 {  
   string countryName = string.Empty;  
   if (dgvAccounts.SelectedRows.Count > 0)  
      {  
         if (dgvAccounts.CurrentRow.Cells[1].Value != null)  
      {  
            countryName = dgvAccounts.CurrentRow.Cells[1].Value.ToString();                   
         }        
   }  
 }  
This will ensure that databinding has finished.
Cheers!

0 comments:

Post a Comment