Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# DataGridViewColumn.CellTemplate如何获取参数?_C#_Datagridview_Parameters - Fatal编程技术网

C# DataGridViewColumn.CellTemplate如何获取参数?

C# DataGridViewColumn.CellTemplate如何获取参数?,c#,datagridview,parameters,C#,Datagridview,Parameters,我想创建我的DataGridViewCell,我已经从DataGridViewTextBoxCell创建了一个子类,名为MyDGVCell。但是我想把一些参数传递给MyDGVCell 如果没有参数,一切都很简单: myDGV.CellTemplate = new MyDGVCell(); 但我想传递参数,所以MyDGVCell的构造函数必须接受一个参数。我的代码是: myDGV.CellTemplate = new MyDGVCell(aValue); 现在可以了,但当我将dataTable

我想创建我的
DataGridViewCell
,我已经从
DataGridViewTextBoxCell
创建了一个子类,名为
MyDGVCell
。但是我想把一些参数传递给
MyDGVCell

如果没有参数,一切都很简单:

myDGV.CellTemplate = new MyDGVCell();
但我想传递参数,所以MyDGVCell的构造函数必须接受一个参数。我的代码是:

myDGV.CellTemplate = new MyDGVCell(aValue);
现在可以了,但当我将dataTable绑定到myDGV时,它会报告错误:
未找到无参数构造函数
。我已经检查出这是由于我的
MyDGVCell
,它确实没有无参数构造函数

因此,我的问题是:如何将参数传递给
DataGridViewCell
?若需要无参数构造函数,如何在运行时传递参数

任何建议都会很有帮助,非常感谢

---------编辑---------

为了简化我的问题,我创建了一个新的Windows窗体项目,将dataGridView1拖动到我的窗体1,并在Form_Load事件中生成以下代码:

    private void Form1_Load(object sender, EventArgs e)
    {
        dataGridView1.Columns.Add("dodo", "dodo");

        dataGridView1.Columns[0].CellTemplate = new MyCell("prop"); //line 1
        //dataGridView1.Columns[0].CellTemplate = new DataGridViewTextBoxCell(); //line 2

        dataGridView1.Rows.Add("try make cell");
    }
这是我定制的DataGridViewCell

class MyCell : DataGridViewTextBoxCell
{
    public string MyProperty { get; set; }

    public MyCell(string myProp)
        : base()
    {
        this.MyProperty = myProp;
    }
}
结果很有趣,如果我在第1行使用代码(使用我自己的单元格),dataGridView不会创建行,但是如果我使用第2行代码(普通TextBoxCell),它会创建行

此外,如果我使用我的单元格,当我在添加的新单元格中输入某些内容时,它会报告相同的错误:没有为该项目找到无参数构造函数


那个么如何在运行时将参数传递给单元格呢?谢谢

因为没有人给出任何答案,我想分享我的解决方案。我不知道这是否是最好的方法,但它是有效的。最后,我从
DataGridViewTextBoxCellColumn
设置了一个类,然后为这个column类创建了一个属性。在
MyCell
类中,我在初始化这个单元格时重写了一个方法。然后我使用this.owningColumn.MyPropertyFromColumn来获得我想要的。实际上,这个单元格可以从它所属的列中随处获取这个参数


似乎单元格必须具有无参数构造函数。因此,我想这是在运行时从其所属列获取参数的唯一方法。

我找到了这个替代解决方案

在扩展DataGridViewCell类的类中,可以将必须在构造函数中传递的参数添加为属性,然后重写Clone方法。 重写必须调用基本克隆方法,然后将返回的对象强制转换为DataGridViewCell扩展类,然后复制克隆对象中的属性

下面是一个示例代码:

public class DataGridViewBoolCell : DataGridViewImageCell
{
  protected bool YourProperty{ get; private set; }

  public DataGridViewBoolCell( bool yourParameter )
  {
    YourProperty = yourParameter;
  }

  public override object Clone()
  {
    var cloned = base.Clone();
    ((DataGridViewBoolCell)cloned).YourProperty = YourProperty;
    return cloned;
  }
}
我不知道这是否是最好的解决方案,但它对我有效