0
votes

how to change the color in datagridview row when i check the check box in C# windows applications?i have code for select one check box is in header column in datagridview it checks all check boxes and changing background color in a datagridview rows but i want when check one check box and corresponding datagridview row will change color please help me

 private void Form1_Load_1(object sender, EventArgs e)
    {
        this.ckBox.CheckedChanged += new System.EventHandler(this.ckBox_CheckedChanged);
        this.dataGridView1.Controls.Add(ckBox);   
    }

    void ckBox_CheckedChanged(object sender, EventArgs e)
    {
        for (int j = 0; j < this.dataGridView1.RowCount; j++)
        {
            this.dataGridView1[2, j].Value = this.ckBox.Checked;
        }
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            DataGridViewCheckBoxCell check = row.Cells["Chk"] as DataGridViewCheckBoxCell;
            if (Convert.ToBoolean(check.Value) == true)
                row.DefaultCellStyle.BackColor = Color.Wheat;
            else
                row.DefaultCellStyle.BackColor = Color.White;
        }
        this.dataGridView1.EndEdit();
    }
1

1 Answers

0
votes

The code to add the CheckBox to the header works pretty well already.

To align the CheckBox to the right you need to calculate the position maybe like this:

    ckBox.Location = new Point(rect.Right - ckBox.Width - 4, rect.Top + 4);

I have added a few pixels padding. You will want to make the column wide enough to prevent the CheckBox overlapping the header text.

But you will need to repeat the alignment whenever the user changes a column's width or the column order or when new columns get added.

So I suggest to move the alignment code into a function you can call when needed:

void layoutCheckBox()
{
    Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(2, -1, true);
    ckBox.Location = new Point(rect.Right - ckBox.Width - 4, rect.Top + 4);
}

For example here:

private void dataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
{
    layoutCheckBox();
}

And then some, as mentioned; depending on what the user can do..

As for the CheckChanged code it seems to work, provided the cells in column Chk indeed all are DataGridViewCheckBoxCells..