Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/269.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C#windows应用程序中选中复选框时,如何更改datagridview行中的颜色?_C#_Checkbox_Datagridview_Windows Applications - Fatal编程技术网

在C#windows应用程序中选中复选框时,如何更改datagridview行中的颜色?

在C#windows应用程序中选中复选框时,如何更改datagridview行中的颜色?,c#,checkbox,datagridview,windows-applications,C#,Checkbox,Datagridview,Windows Applications,当我选中C#windows应用程序中的复选框时,如何更改datagridview行中的颜色?我有选择一个复选框的代码在datagridview的标题列中,它选中所有复选框并更改datagridview行中的背景色,但我想当选中一个复选框和相应的datagridview行时,请更改颜色帮帮我 private void Form1_Load_1(object sender, EventArgs e) { this.ckBox.CheckedChanged += new Sy

当我选中C#windows应用程序中的复选框时,如何更改datagridview行中的颜色?我有选择一个复选框的代码在datagridview的标题列中,它选中所有复选框并更改datagridview行中的背景色,但我想当选中一个复选框和相应的datagridview行时,请更改颜色帮帮我

 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();
    }
private void Form1\u Load\u 1(对象发送方,事件参数e)
{
this.ckBox.CheckedChanged+=新的System.EventHandler(this.ckBox\u CheckedChanged);
this.dataGridView1.Controls.Add(ckBox);
}
void ckBox\u CheckedChanged(对象发送方,事件参数e)
{
对于(int j=0;j
复选框添加到标题的代码已经非常有效了

要向右对齐
复选框
,您需要计算位置,如下所示:

    ckBox.Location = new Point(rect.Right - ckBox.Width - 4, rect.Top + 4);
我添加了一些像素填充。您需要使列足够宽,以防止
复选框
与标题文本重叠

但是,每当用户更改列的宽度或列的顺序,或者添加新列时,您都需要重复对齐

因此,我建议将对齐代码移动到一个可以在需要时调用的函数中:

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

private void dataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
{
    layoutCheckBox();
}
还有一些,如前所述;取决于用户可以做什么

至于
CheckChanged
代码,如果列
Chk
中的单元格确实都是
DataGridViewCheckBoxCells
,它似乎可以工作。

此链接可能会帮助您