Quantcast
Channel: Windows Forms Data Controls and Databinding forum
Viewing all articles
Browse latest Browse all 2535

How to add user control to datagridview cell c#

$
0
0

i was searching trick to add user control to datagridview cell and found the below code. i just copy paste the code but when i try to add the CustomColumn then i got error.

this way i try to add CustomColumn column to grid.

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);
            }    
        }
    }
} 

Please show me how to use the above code for adding custom column. i created a user control and name was CustomUserControl but no luck.

thanks


Viewing all articles
Browse latest Browse all 2535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>