Datagridview复选框单元格更改按钮和画线的颜色

时间:2017-08-08 15:40:25

标签: c# winforms checkbox datagridview colors

问题是通过单击datagridview复选框单元格来更改按钮的颜色,并通过相同的复选框单击突出显示绘制的箭头。

现在正在使用TaW的解决方案。感谢那。

    private void dataGridView1_CellContentClick(object f_sender_dgv, DataGridViewCellEventArgs f_event_dgv)
    {     

        DataGridView dataGridView1 = f_sender_dgv as DataGridView;


        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);

        DataGridViewCell cb_1 = dataGridView1[2, 0];//
        //DataGridViewCell cb_1 = dataGridView1[f_event_dgv.ColumnIndex , f_event_dgv.RowIndex];

        if (cb_1 is DataGridViewCheckBoxCell)
        {
            bool c = (bool)(cb_1 as DataGridViewCheckBoxCell).Value;
            button_gv_1.BackColor = c ? Color.Yellow : Color.Snow;
            button_v_5.BackColor = c ? Color.Yellow : Color.Snow;
        }
        this.Invalidate();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        Graphics g;
        g = e.Graphics;
        Pen myPen = new Pen(Color.Black);
        myPen.Width = 1;
        myPen.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
        //g.DrawLine(myPen1, 400, 700, 1000, 100);//(X_start, Y_start, X_ende, Y_ende)

        // test if data is loaded:
        if (!(dataGridView1.RowCount > 0 && dataGridView1.ColumnCount > 2)) return;

        //use the correct indices = [e.ColumnIndex, e.RowIndex]
        DataGridViewCell cell = dataGridView1[2,0];  
        if (cell is DataGridViewCheckBoxCell && cell.Value != null)
        {
            bool c = (bool)(cell as DataGridViewCheckBoxCell).Value;
            Pen myPen1 = c ? Pens.Yellow : Pens.Black;
            g.DrawLine(myPen1, 400, 700, 1000, 100);//(X_start, Y_start, X_ende, Y_ende)
        }
    }

1 个答案:

答案 0 :(得分:1)

以下是button.BackColor的等效代码:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);

    DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];
    if (cell is DataGridViewCheckBoxCell)
    {
        bool c = (bool) (cell as DataGridViewCheckBoxCell).Value;
        button1.BackColor = c ? Color.Yellow: Color.Snow;
        this.Invalidate();
    }
}

Paint事件可以或多或少地以相同的方式测试单元格:

protected override void OnPaint(object sender, PaintEventArgs e)
{
    // test if data are loaded:
    if (! (dataGridView1.RowCount > 0  && dataGridView1dgv.ColumnCount > 2)) return;

    DataGridViewCell cell = dataGridView1[0, 2];  // <-- use the correct indices!!
    if (cell is DataGridViewCheckBoxCell && cell.Value != null)
    {
        bool c = (bool)(cell as DataGridViewCheckBoxCell).Value;

        Pen myPen = c ? Pens.Yellow : Pens.Snow;
        e.Graphics.DrawLine(myPen, 160, 285, 250, 285);
    }
}

..或测试你设置的班级标志。