c# - 添加获取设置DatagridViewTextBoxCell

标签 c# datagridview

我尝试添加一个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类型:

Custom DGV 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/

相关文章:

c# - WebClient Unicode - 哪个UTF8?

c# - 如何在ItemsControl中显示弹出窗口

c# - Properties.Settings.Save() 仅在第一次调用时保存

c# Datagridview (Winform) 基于相邻单元格值的单元格着色

c# - 在 DataGridView 中的特定单元格中设置 ComboBox

c# - 在 Xamarin Native Android 应用程序中显示 admob 横幅和插页式广告

c# - 如果错误已经逐字段显示,如何不显示 ASP MVC ValidationSummary?

c# - PInvoke - 如何编码 'SomeType* []'?

c# - DataGridView 单元格对齐不起作用

.net - 如何禁用整个 .net DataGridView 列的工具提示