views:

387

answers:

2

I have a DataGridView and I'm drawing TreeView-style dotted lines on the first cell of each row during its RowPostPaint event. When the first cell (which is a DataGridViewTextBoxCell) is in editing mode, the lines aren't drawn. How do I handle painting for the editing control? The standard editing control doesn't have a Paint event, and I don't want to create a new type of cell if I can avoid doing so.

A: 

Try to handle DataGridView.CellPainting event.

Veton
No joy - it gets called, but it doesn't paint anything visible when the cell is in editing mode.
Simon
+1  A: 

I solved a similar problem by creating a custom cell type, and shrinking the editing control as Bryan described. It's not terribly difficult, and it's the only way I'm aware of to keep the editing control from drawing on top of everything.

Something like this ought to work for you:

public class PaintAccommodatingTextBoxCell : DataGridViewTextBoxCell
{
 // Adjust the editing panel, so that custom painting isn't
 // drawn over when cells go into edit mode.
 public override Rectangle PositionEditingPanel(Rectangle cellBounds, Rectangle cellClip, DataGridViewCellStyle cellStyle, bool singleVerticalBorderAdded, bool singleHorizontalBorderAdded, bool isFirstDisplayedColumn, bool isFirstDisplayedRow)
 {
  // First, let base class do its adjustments
  Rectangle controlBounds = base.PositionEditingPanel(cellBounds, cellClip, cellStyle, singleVerticalBorderAdded, singleHorizontalBorderAdded, isFirstDisplayedColumn, isFirstDisplayedRow);

  // Shrink the bounds here...

  return controlBounds;
 }
}

public class PaintAccommodatingTextBoxColumn : DataGridViewTextBoxColumn
{
 PaintAccommodatingTextBoxCell templateCell;

 public PaintAccommodatingTextBoxColumn()
 {
  templateCell = new PaintAccommodatingTextBoxCell();
 }

 public override DataGridViewCell CellTemplate
 {
  get
  {
   return templateCell;
  }
  set
  {
   PaintAccommodatingTextBoxCell newTemplate = value as PaintAccommodatingTextBoxCell;
   if (newTemplate == null)
    throw new ArgumentException("Template must be a PaintAccommodatingTextBoxCell");
   else
    templateCell = newTemplate;
  }
 }
}
Andrew Watt
While working on the same issue I found that the cellBounds parameter needed to be modified before calling base.PositionEditingPanel rather than simply modifying the return value. Otherwise the EditingControl would be resized, but not the EditingPanel which would obscure the custom cell painting.
asponge