How to paint custom control on datagridviewcell?

微笑、不失礼 提交于 2019-12-06 04:32:13

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 or VisualStyleRenderer (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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!