splattne
splattne

Reputation: 104040

Windowsforms: How to draw lines/bars on a DataGridView?

I'm using a DataGridView in a Windows application (.NET 3.5) showing some colored bars (basically "tasks in time"):

DataGridView 1 http://img195.imageshack.us/img195/879/datagridview1.png

What I need now is, to show a custom graphical "completed" bar on the cells depending on a percentage value. Here is a photoshopped image:

DataGridView 2 http://img38.imageshack.us/img38/5615/datagridview2.png

Any hint how I could approach the problem or a creative solution?

Thanks!

Edit: I had to redraw the cell, becuase it gets "lost." Here is the (VB.NET) code that works:

Private Sub DataGridView_CellPainting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles DataGridView.CellPainting

    If e.ColumnIndex < FIRST_DATA_COLUMN OrElse e.RowIndex < 0 Then Return
    If e.Value Is Nothing Then Return

    Dim BarValue As Integer = DirectCast(e.Value, Integer)
    If BarValue = 0 Then Return

    Dim BackColorBrush As New SolidBrush(e.CellStyle.BackColor)
    Dim GridBrush As New SolidBrush(Me.DataGridView.GridColor)
    Dim GridLinePen As New Pen(GridBrush)

    ' -- Erase the cell
    e.Graphics.FillRectangle(BackColorBrush, e.CellBounds)

    ' -- Draw the grid lines (only the right and bottom lines; DataGridView takes care of the others)
    e.Graphics.DrawLine(GridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1)
    e.Graphics.DrawLine(GridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1)

    ' -- Paint progress bar
    Dim ProgressBarBrush As New SolidBrush(Color.Green)
    Dim CellProgressBarRect As New Rectangle(e.CellBounds.X, e.CellBounds.Y + CELL_HEIGHT - PROGRESS_BAR_HEIGHT, BarValue, PROGRESS_BAR_HEIGHT)
    e.Graphics.FillRectangle(ProgressBarBrush, CellProgressBarRect)

    e.Handled = True

End Sub

Upvotes: 0

Views: 5598

Answers (1)

James
James

Reputation: 82096

You will have to do a Custom Draw on the Cell. Have a look at the Cell Painting event.

Upvotes: 1

Related Questions