0

I'm trying to check if the dataGridView CheckBox column is checked, and when I run the program it gives me this an error as:

Object reference not set to an instance of an object

anyone to help?

C# code:

for(int i = 0; i < payRollDataGrid.Rows.Count; i++)
{
   bool isCellChecked = (bool)payRollDataGrid.Rows[i].Cells[0].Value;

   if (isCellChecked == true)
   {
   MessageBox.Show(payRollDataGrid.Rows[i].Cells[1].Value + "Cheked");
   }         
}
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
  • 4
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Izzy Aug 15 '18 at 08:53
  • one of the .Cells[0] or .Cells[1] is null and has no value ... – Nima Derakhshanjan Aug 15 '18 at 08:57
  • That means is unchecked, but my aim is to select some of the Cells, not al the Cell, and Cell[1] is not null, it has the values. – Shedrack Ikwabe Aug 15 '18 at 09:04
  • which event are u executing this code like cellendedit, cellclick event – senthilkumar2185 Aug 15 '18 at 09:07
  • I check first the checkBox and press the Button – Shedrack Ikwabe Aug 15 '18 at 09:19
  • private void CheckBtn_Click(object sender, EventArgs e) { for(int i = 0; i < payRollDataGrid.Rows.Count; i++) { bool isCellChecked = (bool)payRollDataGrid.Rows[i].Cells[0].Value; if (isCellChecked == true) { MessageBox.Show(payRollDataGrid.Rows[i].Cells[1].Value + "Cheked"); } } } – Shedrack Ikwabe Aug 15 '18 at 09:19
  • foreach(DataGridViewRow currentRow in payRollDataGrid.Rows) { if ((bool)currentRow.Cells[0].Value) { MessageBox.Show(currentRow.Cells[0].Value + "Cheked"); } else if((bool)currentRow.Cells[1].Value)){ MessageBox.Show(currentRow.Cells[1].Value + "Cheked"); } } – senthilkumar2185 Aug 15 '18 at 10:04

1 Answers1

0

Try below code:

foreach(DataGridViewRow currentRow in payRollDataGrid.Rows)
{                
  if ((bool)currentRow.Cells[0].Value)
  {
    MessageBox.Show(currentRow.Cells[1].Value + "Cheked");
  }
}
some ediot
  • 35
  • 1
  • 8