devtunis devtunis - 21 days ago 12
C# Question

Button in DataGridView with condition C#

I want to ADD button to a column in DataGridView...But with a condtion : just when the color of the ROW is RED,
This is datagridview:

enter image description here

Now, all the button in Column 'Check-Out' work...with the Red Row or the White Row...my code:

int row = (int)this.dataGridView1.CurrentCell.OwningRow.Cells[0].Value;

if (MessageBox.Show("Check-out?",
"Message de confirmation",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{ MessageBox.Show("Success!!");
}


For just the button work with Red ROW,
I try this code :

if (dataGridView1.SelectedRows[0].DefaultCellStyle.BackColor == Color.Red)
{
int row = (int)this.dataGridView1.CurrentCell.OwningRow.Cells[0].Value;

if (MessageBox.Show("Check-out?",
"Message de confirmation",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{MessageBox.Show("Success!!");
}


I have ERROR: The index was off limits. It must not be negative and must be less than the size of the collection. in line:

if (dataGridView1.SelectedRows[0].DefaultCellStyle.BackColor == Color.Red)


ERROR:

enter image description here

Thanks,

Answer

I find the correct answer: I should modifie the line :

if (dataGridView1.SelectedRows[0].DefaultCellStyle.BackColor == Color.Red)

with :

 if(dataGridView1.CurrentRow.DefaultCellStyle.BackColor==Color.Red)

So we use DataGridView.CurrentRow

Comments