twenty94470
twenty94470

Reputation: 105

Add Get Set DatagridViewTextBoxCell

I try to add a get; set; property into my DataGridViewTextBoxCell but it's not working

For that I create my public class :

public class MyData : DataGridViewTextBoxCell
    {
        public string Url { get; set; }
    }

And in my main code

dataGridView1.Rows.Add();
MyData CustomCell = (MyData)dataGridView1.Rows[0].Cells[0];
CustomCell.Url = "";

During code execution I have the error on the line MyData CustomCell = (MyData)dataGridView1.Rows[0].Cells[0];

System.InvalidCastException : 'Unable to cast Object type System.Windows.Forms.DataGridViewTextBoxCell' into type .MyData'.'

Do you have a clue to add my custom property in datagridview cell ?

Thanks a lot

Upvotes: 2

Views: 475

Answers (1)

user10216583
user10216583

Reputation:

You also need to create a Column class and set the CellTemplate property to a new instance of the Cell class:

public class MyDataGridViewTextBoxColumn : DataGridViewTextBoxColumn
{
    public MyDataGridViewTextBoxColumn() =>
        CellTemplate = new MyDataGridViewTextBoxCell();
}

And your Cell class should be like:

public class MyDataGridViewTextBoxCell : DataGridViewTextBoxCell
{
    public MyDataGridViewTextBoxCell() { }

    public string Url { get; set; }

    //Don't forget to clone your new properties.
    public override object Clone()
    {
        var c = base.Clone();
        ((MyDataGridViewTextBoxCell)c).Url = Url;
        return c;
    }
}

Now you can add the new Column type by the designer:

Custom DGV Column

Or through the code:

var myNewTBC = new MyDataGridViewTextBoxColumn
{
    HeaderText = "My Custom TB",
};
dataGridView1.Columns.Add(myNewTBC);

Assuming that the custom text box column is the first column in the DGV, then you can get a Cell as follows:

var myTB = (MyDataGridViewTextBoxCell)dataGridView1.Rows[0].Cells[0];
myTB.Url = "...";

Upvotes: 2

Related Questions