问题
I want to host a custom control for datagridviewcell
.
the only good reference i have was http://msdn.microsoft.com/en-us/library/7tas5c80.aspx
However, i want the cell to display my own usercontrol instead on
public class CustomCell : DataGridViewTextBoxCell
{
protected override void Paint(System.Drawing.Graphics graphics,
System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds,
int rowIndex, DataGridViewElementStates cellState, object value, object
formattedValue, string errorText, DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
{
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value,
formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
}
}
Can anyone guide me how to do it ?
回答1:
In order to save on resources, the cells in a DataGridView
control spend most of their time in display mode, only changing to edit mode when the user enters the cell using the mouse or keyboard. The example you referred to in your question is regarded as best practice, because the editing control (in that case, a DateTimePicker
, but could just as easily be your own custom user control) only ever appears in edit mode, and thus only for one cell at a time.
When the cell is not in edit mode, it should render an equivalent representation of its value using logic inside the Paint
method of your subclass of DataGridViewCell
. You could do this in one of several ways:
- Simply draw text or an image onto the bounds of the cell based on its value; don't try to replicate the way that the editing control looks.
- Simulate the appearance of the editing control using
ControlPaint
orVisualStyleRenderer
(note: this involves a lot of extra work). - Move the painting code from your custom user control into a utility class, so that both it and the cell can use the same painting code.
In most cases, the first option will be sufficient; only attempt one of the other approaches if it is important for the cell to look EXACTLY the same as your editing control.
来源:https://stackoverflow.com/questions/13118251/how-to-paint-custom-control-on-datagridviewcell