【问题标题】:Custom ComboBox Column for DataGridViewDataGridView 的自定义组合框列
【发布时间】:2012-12-11 15:23:19
【问题描述】:

我们有一个自定义组合框,用于显示一些形状而不是文本的表单。为此,我所要做的就是重写 OnDrawItem 函数,它会显示我们想要的内容。这是一个sn-p供参考:

protected override void OnDrawItem(DrawItemEventArgs e)
{
    base.OnDrawItem(e);

    e.DrawBackground();
    if (e.Index >= 0)
    {
        Brush brush = new SolidBrush(Color.LightGray);

        int size = this.Height/2;
        int origenX = e.Bounds.X + 1;
        int origenY = e.Bounds.Y + 3;
        System.Drawing.Drawing2D.GraphicsPath path =
                new System.Drawing.Drawing2D.GraphicsPath();
        switch (e.Index)
        {
            case 0:                            
                e.Graphics.FillRectangle(brush, origenX, origenY, size, size);                            
                Rectangle r = new Rectangle(origenX, origenY, size, size);                            
                ControlPaint.DrawBorder(e.Graphics, r, Color.Black,
                                        ButtonBorderStyle.Solid);
                break;
            case 1:
                path.AddEllipse(origenX, origenY, size, size);
                e.Graphics.FillPath(brush, path);
                e.Graphics.DrawPath(Pens.Black, path);
                break;
        }
    }
}

因此,如果您将其添加到表单中并将几个项目添加到您的集合中,您会在下拉菜单中看到一个正方形和一个圆形。

好的,我现在要做的就是将这个相同的组合框添加到 DataGridView。我知道这个控件有一个 DataGridViewComboBoxColumn。我试图扩展控件,但是,我没有看到要覆盖的这个 OnDrawItem 函数。我想有类似的东西吗? 任何帮助,将不胜感激。 谢谢!

【问题讨论】:

    标签: c# winforms combobox datagridcomboboxcolumn


    【解决方案1】:

    您需要将 DataGridViewComboBox 解释为您的自定义组合框。

    private void dgTest_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
            {
                if (dgTest.CurrentCell.ColumnIndex == 0) // Which column ever is your DataGridComboBoxColumn
                {
                    // This line will enable you to use the DataDridViewCOmboBox like your
                    // Custom ComboBox.
                    CustomComboBox combo = e.Control as CUstomComboBox;
    
                }
            }
    

    【讨论】:

    • 感谢您的帮助!不幸的是,不这样做不会。我确实先尝试过。这个解决方案有两个问题,一个是它只显示项目中的数据,在我的情况下基本上是 ID。其次,一旦退出编辑模式,它不会显示任何内容,因为表格本身不知道要绘制什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 2015-10-23
    • 2013-11-18
    相关资源
    最近更新 更多