Drawing a filled circle or rectangle inside a DataGridViewCell in C# Winforms

前端 未结 3 1938
有刺的猬
有刺的猬 2021-01-04 22:46

I want to draw a small filled circle in the center of a DataGridViewCell. A rectangle can do the trick as well. I assume I must do it in the CellPainting event.

3条回答
  •  情书的邮戳
    2021-01-04 23:29

    I finally resolved it. I drew a filled rectangle with the same size as the checkbox and in the same location.

    I did the following:

    First, I change the DataGridViewCheckBoxCell to DataGridViewTextBoxCell to hide the checkbox.

    DataGridViewTextBoxCell blank_cell = new DataGridViewTextBoxCell();
    dgv_Cuotas.Rows[row.Index].Cells["Seleccionar"] = blank_cell;
    dgv_Cuotas.Rows[row.Index].Cells["Seleccionar"].Style.ForeColor = Color.Transparent;
    dgv_Cuotas.Rows[row.Index].Cells["Seleccionar"].Style.SelectionForeColor = Color.Transparent;
    

    Be sure of selecting transparent forecolor so as not to see "False" in the Cell.

    After that, I just painted the rectangle in the cell using the cellpainting event:

    if (dgv_Cuotas.Columns[e.ColumnIndex].Name == "Seleccionar" && Convert.ToDecimal(dgv_Cuotas.Rows[e.RowIndex].Cells["Restante"].Value) == 0)
                {
                    Color c1 = Color.FromArgb(255, 113, 255, 0);
                    Color c2 = Color.FromArgb(255, 2, 143, 17);
    
                    LinearGradientBrush br = new LinearGradientBrush(e.CellBounds, c1, c2, 90, true);
                    ColorBlend cb = new ColorBlend();
                    cb.Positions = new[] { 0, (float)1 };
                    cb.Colors = new[] { c1, c2 };
                    br.InterpolationColors = cb;
    
                    Rectangle rect = new Rectangle(e.CellBounds.Location.X + 4, e.CellBounds.Location.Y + 4, 13, 13);
    
                    e.Graphics.FillRectangle(br, rect);
                    e.PaintContent(rect);
                    e.Handled = true;
                }
    

    You can get the location you want by changing the Location.X and Location.Y values like I did.

    enter image description here Hope that helps somebody!

提交回复
热议问题