代码之家  ›  专栏  ›  技术社区  ›  Rob

如何在DataGridViewCell中绘制自定义组合框?

  •  1
  • Rob  · 技术社区  · 16 年前

    我有个习惯 ComboBox 我要在中使用的控件 DataGridViewCell . 我第一次继承 单元格 我正在努力克服 Paint() 绘制方法 组合框 在牢房里。

    我的问题是继承后 DataGridViewColumn 设置 CellTemplate 属性的新实例 CustomDataGridViewCell 类,单元格为灰色,没有内容。

    这个 cBox 类变量在对象ctor中实例化。

    protected override void Paint(Graphics graphics, Rectangle clipBounds, 
       Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, 
       object value, object formattedValue, string errorText, 
       DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle borderStyle,
       DataGridViewPaintParts paintParts)
    {
       // Call MyBase.Paint() without passing object for formattedValue param
       base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, 
           "", errorText, cellStyle, borderStyle, paintParts);
        
       // Set ComboBox properties
       this.cBox.CheckOnClick = true;
       this.cBox.DrawMode = System.Windows.Forms.DrawMode.Normal;
       this.cBox.DropDownHeight = 1;
       this.cBox.IntegralHeight = false;
       this.cBox.Location = new System.Drawing.Point(cellBounds.X, cellBounds.Y);
       this.cBox.Size = new System.Drawing.Size(cellBounds.Width, cellBounds.Height);
       this.cBox.ValueSeparator = ", ";
       this.cBox.Visible = true;
       this.cBox.Show();
    }
    

    我怎么能正确地画 组合框 在牢房里?

    1 回复  |  直到 13 年前
        1
  •  1
  •   Rob    13 年前

    我做了相当简单的改变来解决我的问题。

    我必须把坐标改成相对于窗户的坐标,而不是 DataGridView ,呼叫 Controls.Add() 对于所属窗体,并将控件重新定位到 数据表格控件 :

    protected override void Paint(Graphics graphics, Rectangle clipBounds, 
       Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, 
       object value, object formattedValue, string errorText, 
       DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle borderStyle, 
       DataGridViewPaintParts paintParts)
    {
       // Just paint the border (because it shows outside the ComboBox bounds)
       this.PaintBorder(graphics, clipBounds, cellBounds, cellStyle, borderStyle);
    
       int cellX = this.DataGridView.Location.X + cellBounds.X;
       int cellY = this.DataGridView.Location.Y + cellBounds.Y;
    
       // Create ComboBox and set properties
       this.cBox = new CheckedComboBox();
       this.cBox.DropDownHeight = 1;
       this.cBox.IntegralHeight = false;
       this.cBox.Location = new Point(cellX, cellY);
       this.cBox.Size = new Size(cellBounds.Width, cellBounds.Height);
       this.cBox.ValueSeparator = ", ";
        
       // Add to form and position in front of DataGridView
       this.DataGridView.FindForm.Controls.Add(this.cBox);
       this.cBox.BringToFront();
    }
    
    推荐文章