您可以创建一个继承自DataGridViewColumnHeaderCell 的自定义标题单元格。然后重写它的Paint 方法并在标题上绘制一个按钮。
先调用base.Paint方法,然后在合适的位置绘制按钮。
要绘制这样的按钮,您可以使用ButtonRenderer.DrawButton 并使用图片作为下拉菜单。您也可以使用ComboBoxRenderer.DrawDropDownButton 为您绘制下拉菜单。
还要在网格中显示它,将自定义标题单元格的实例分配给所需列的 HeaderCell 属性:
this.dataGridView1.Columns[0].HeaderCell = new FilterDataGridViewColumnHeader();
上面的截图是用这段代码创建的:
public class FilterDataGridViewColumnHeader : DataGridViewColumnHeaderCell
{
protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates dataGridViewElementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
{
base.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
ComboBoxRenderer.DrawDropDownButton(graphics, new System.Drawing.Rectangle(cellBounds.Right - 16, 4, 14, cellBounds.Height - 6), System.Windows.Forms.VisualStyles.ComboBoxState.Normal);
}
}