我尝试添加一个get; set;
属性到我的 DataGridViewTextBoxCell 但它不起作用
为此,我创建了我的公共(public)类(class):
public class MyData : DataGridViewTextBoxCell
{
public string Url { get; set; }
}
在我的主代码中
dataGridView1.Rows.Add();
MyData CustomCell = (MyData)dataGridView1.Rows[0].Cells[0];
CustomCell.Url = "";
在代码执行期间我遇到了错误
MyData CustomCell = (MyData)dataGridView1.Rows[0].Cells[0];
System.InvalidCastException : 'Unable to cast Object type System.Windows.Forms.DataGridViewTextBoxCell' into type .MyData'.'
您知道如何在 datagridview 单元格中添加我的自定义属性吗?
非常感谢
最佳答案
您还需要创建一个 Column
类并将 CellTemplate
属性设置为 Cell
类的新实例:
public class MyDataGridViewTextBoxColumn : DataGridViewTextBoxColumn
{
public MyDataGridViewTextBoxColumn() =>
CellTemplate = new MyDataGridViewTextBoxCell();
}
你的 Cell
类应该是这样的:
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;
}
}
现在您可以由设计者添加新的Column
类型:
或者通过代码:
var myNewTBC = new MyDataGridViewTextBoxColumn
{
HeaderText = "My Custom TB",
};
dataGridView1.Columns.Add(myNewTBC);
假设自定义文本框列是DGV中的第一列,那么可以得到一个Cell
,如下所示:
var myTB = (MyDataGridViewTextBoxCell)dataGridView1.Rows[0].Cells[0];
myTB.Url = "...";
关于c# - 添加获取设置DatagridViewTextBoxCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59904669/