如何将DataGridViewCell转换为Control

Vin*_*ent 2 c# datagridview type-conversion

我试图将DataGridView单元格转换为控件:

Control dat = new Control();
dat = Convert.ChangeType(dataGridView1[colIndex,rowIndex], typeof(Control));
Run Code Online (Sandbox Code Playgroud)

我从索引代码中获取colIndex和rowIndes的值.问题是即使我尝试了很多代码来转换,它也行不通.

我得到的例外是:

无法将对象隐式转换为控件.存在显式转换(你是否错过了演员?)

Dav*_*all 6

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

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

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

private void dataGridView1_EditingControlShowing(object sender, 
    DataGridViewEditingControlShowingEventArgs e)
{
    Control c = e.Control;
}
Run Code Online (Sandbox Code Playgroud)

如果你想在其他时间访问控件,那么(我相信)你运气不好 - 我说这主要基于MSDN文档中的引用DataGridViewEditingControlShowing:

DataGridView控件一次承载一个编辑控件,并且只要单元格类型在编辑之间不发生更改,就会重新使用编辑控件.