DataGridView - Use Gradiant Brush to format a cell

B

Bart Mermuys

Hi,

Vince P said:
How could I format the background of a DataGridView cell with a gradiant
brush?

Depends on which cells you want to fill with gradient brush. Have a look at
:
DataGridView.RowPrePaint and / or
DataGridView.CellPainting

The following code applies a gradient background to each cell within the
first column that isn't selected:

dataGridView1.CellPainting +=
new DataGridViewCellPaintingEventHandler(dataGridView1_CellPainting);

void dataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
if ((e.ColumnIndex==0) && (e.RowIndex != -1) &&
(e.State & DataGridViewElementStates.Selected)!=
DataGridViewElementStates.Selected)
{
// fill gradient background
Brush gradientBrush = new System.Drawing.Drawing2D.LinearGradientBrush(
e.CellBounds, Color.Blue, Color.BlueViolet,
System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal);
e.Graphics.FillRectangle(gradientBrush, e.CellBounds);
backbrush.Dispose();

// paint rest of cell
e.Paint(e.CellBounds, DataGridViewPaintParts.Border |
DataGridViewPaintParts.ContentForeground);
e.Handled = true;
}
}


HTH,
Greetings
 
V

Vince P

Thanks a bunch man.. with your help, I got it to work

This is the result

http://home.comcast.net/~vincep1974/images/gradiant.png

Here is my code (in my case I only wanted the gradiant formatting if some
word in the cell matched a list of words in a collection)



private void gridChannel_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
bool isHandled = false;
if (e.RowIndex >= 0 && e.ColumnIndex == 2)
{
if (gridChannel[e.ColumnIndex, e.RowIndex].Value != null &&
IrcBase.MDIParentForm.AppSettings.ProfileWordWatchSettingsCol.CheckForMatch(gridChannel[e.ColumnIndex,
e.RowIndex].Value.ToString()))
{
System.Drawing.Drawing2D.LinearGradientBrush lBrush =
new System.Drawing.Drawing2D.LinearGradientBrush(e.CellBounds,
e.CellStyle.BackColor,
IrcBase.MDIParentForm.AppSettings.ProfileMatchCellColor,
System.Drawing.Drawing2D.LinearGradientMode.Horizontal);
e.Graphics.FillRectangle(lBrush, e.CellBounds);
lBrush.Dispose();
e.Paint(e.CellBounds, DataGridViewPaintParts.Border |
DataGridViewPaintParts.ContentBackground |
DataGridViewPaintParts.ContentForeground | DataGridViewPaintParts.ErrorIcon
| DataGridViewPaintParts.Focus);
e.Handled = true;
isHandled = true;

}

}
if (!isHandled)
{
e.Handled = false;
}





}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top