3

我正在寻找将用户控件添加到datagridview单元格的技巧,并找到了以下代码。我只是复制粘贴代码,但是当我尝试添加时,CustomColumn我得到了错误。

这样我尝试将CustomColumn列添加到网格。

private void button1_Click(object sender, EventArgs e)
{
    CustomColumn cc=new CustomColumn();
    dataGridView1.Columns.Add(cc);
    dataGridView1.Rows.Add("");
}

public class CustomColumn : DataGridViewColumn {
    public CustomColumn() : base(new CustomeCell()) { }
    public override DataGridViewCell CellTemplate
    {
        get
        {
            return base.CellTemplate;
        }
        set
        {
            // Ensure that the cell used for the template is a CalendarCell.
            if (value != null &&
                !value.GetType().IsAssignableFrom(typeof(CustomeCell)))
            {
                throw new InvalidCastException("It should be a custom Cell");
            }
            base.CellTemplate = value;
        }
    }        
}
public class CustomeCell : DataGridViewCell
{
    public CustomeCell() : base() { }
    public override Type ValueType
    {
        get
        {
            return typeof(CustomUserControl);
        }
    }
    protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
    {
        CustomUserControl ctrl = (CustomUserControl)value;
        Bitmap img = new Bitmap(cellBounds.Width, cellBounds.Height);
        ctrl.DrawToBitmap(img, new Rectangle(0, 0, ctrl.Width, ctrl.Height));
        graphics.DrawImage(img, cellBounds.Location);
    }
    protected override void OnClick(DataGridViewCellEventArgs e)
    {
        List<InfoObject> objs = this.DataGridView.DataSource as List<InfoObject>;
        if (objs != null) 
        {
            if (e.RowIndex >= 0 && e.RowIndex < objs.Count) {
                CustomUserControl ctrl = objs[e.RowIndex].Ctrl;
                // Take any action - I will just change the color for now.
                ctrl.BackColor = Color.Red;
                ctrl.Refresh();
                this.DataGridView.InvalidateCell(e.ColumnIndex, e.RowIndex);
            }    
        }
    }
} 

请告诉我如何使用上面的代码添加自定义列。我创建了一个用户控件和名称,CustomUserControl但没有运气。谢谢

4

1 回答 1

-1

发布了一个名为 ColVis 的 DataTables 新插件。ColVis 将在表格旁边设置一个按钮,激活该按钮后将显示表格中的列列表,最终用户可以选择显示或隐藏列。

试试 datatables.net/release-datatables/extras/ColVis/

下载(将提取的文件夹放入 DataTables 发行版中的“extras”文件夹中):datatables.net/releases/ColVis-1.0.1.zip

http://yellowpages.sulekha.com

于 2013-04-01T07:11:24.927 回答