如何将DataGridViewCell转换为控件

本文关键字:控件 转换 DataGridViewCell | 更新日期: 2023-09-27 18:15:15

我正在尝试将DataGridView单元格转换为控件:

Control dat = new Control();
dat = Convert.ChangeType(dataGridView1[colIndex,rowIndex], typeof(Control));

我正在从索引代码中获取colIndex和rowIndes的值。问题是,即使我尝试了许多代码转换,它也不起作用。

我得到的例外是:

不能隐式地将对象转换为控件。存在显式转换(u缺少强制转换吗?)

如何将DataGridViewCell转换为控件

要访问由DataGridViewCell托管的控件,当单元格处于编辑模式时,使用单元格EditingControl属性。

这个属性返回一个System.Windows.Forms.Control

您还可以在DataGridViewEditingControlShowing事件中获得控制- DataGridViewEditingControlShowingEventArgsControl属性是System.Windows.Forms.Control类型。

private void dataGridView1_EditingControlShowing(object sender, 
    DataGridViewEditingControlShowingEventArgs e)
{
    Control c = e.Control;
}

如果你想在其他时间访问控件,那么(我相信)你就不走运了——我说这主要是基于MSDN文档在DataGridViewEditingControlShowing上的引用:

DataGridView控件一次承载一个编辑控件,并且只要单元格类型不变,就重用编辑控件编辑之间。

Convert.ChangeType将无法工作,除非在对象和控件之间定义了转换,当然没有。ChangeType最常用于基本类型,如整数和浮点数。

如果dataGridView1[colIndex, rowIndex]是一个控件,你应该能够使用普通的显式强制转换:dat = (Control) dataGridView1[colIndex, rowIndex]

DataGridView的Item属性(这是您使用行和列索引访问的)是DataGridViewCell类型,它不是从System.Windows.Forms.Control.

继承的。