c# - DatagridViewComboBoxColumn 的自定义绘制

标签 c# winforms datagridview datagridviewcomboboxcell custom-draw

我正在使用 DataGridViewDataGridViewComboBoxColumn,并且我需要在组合框项目的左侧添加图标。我目前正在使用 EditingControlShowing 事件和 ComboBox.DrawItem 事件,如下所示:

private void pFiles_dgvFiles_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control is ComboBox)
    {
    ComboBox cb = (ComboBox)e.Control;                                
    cb.DrawMode = DrawMode.OwnerDrawFixed;
    cb.DrawItem -= combobox1_DrawItem;
    cb.DrawItem += combobox1_DrawItem;
     }
}

private void combobox1_DrawItem(object sender, DrawItemEventArgs e)
{
    // Drawing icon here        
}

问题是只有当单元格处于编辑模式时才会绘制图标。一旦我单击单元格外部的某个位置,CellEndEdit 事件就会被触发,并且单元格将被重新绘制(没有图标)。

我尝试使用 DataGridView.CellPainting 事件来解决此问题,但它导致 DataGridViewComboBoxColumn 的下拉按钮消失。

关于如何在用户完成编辑单元格后绘制图标有什么想法吗?

最佳答案

在 CellPainting 事件中,您可以尝试在现有控件上绘画:

e.PaintBackground(e.ClipBounds, true);
e.PaintContents(e.ClipBounds);

//Draw your stuff

e.Handled = true;

或者查看ComboBoxRenderer类中的DrawDropDownButton方法(或ControlPaint.DrawComboButton用于非视觉样式)。

关于c# - DatagridViewComboBoxColumn 的自定义绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7482534/

相关文章:

c# - List<string> 简单分组和计数?

c# - 从 Windows 窗体应用程序以横向模式打印 SSRS 报告

c# - 获取DataGridView中选定的行

c# - 如何在每个单元格中设置具有不同数据源的 DataGridView ComboBoxColumn?

c# - 使用 autofac 在 azure 上进行数据保护操作失败

c# - 如何对异步/等待示例进行单元测试?

c# - 在 C# WinForms 中,如何摆脱 child 的控制栏?

c# - 游戏的自定义热键

c# - 找不到 DataGridView 的列名

c# - 如果可能,在 C# 中使用 FtpWebRequest 在没有第 3 方 dll 的情况下实现 FTP/SFTP