How to convert a DataGridViewCell to a Control
Solution 1
To access the control that is hosted by a DataGridViewCell
you use the EditingControl
property of the cell when the cell is in editing mode.
This property returns a System.Windows.Forms.Control
.
You can also get at the control within the DataGridViewEditingControlShowing
event - the Control
property of DataGridViewEditingControlShowingEventArgs
is of type System.Windows.Forms.Control
.
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
Control c = e.Control;
}
If you want to access the control at other times then (I believe) you are out of luck - I say that based mainly on this quote from the MSDN docs on DataGridViewEditingControlShowing
:
The DataGridView control hosts one editing control at a time, and reuses the editing control whenever the cell type does not change between edits.
Solution 2
Convert.ChangeType
won't work unless there is a conversion defined between an Object and a Control, which of course there isn't. ChangeType is used most often for primitive types like integers and floats.
If dataGridView1[colIndex, rowIndex] is a Control, you should be able to use ordinary explicit casting: dat = (Control) dataGridView1[colIndex, rowIndex]
Solution 3
The Item property of a DataGridView (this is what you access using row and column indexes) is of type DataGridViewCell, which is not inherited from System.Windows.Forms.Control.
Vincent
Updated on June 22, 2022Comments
-
Vincent over 1 year
I am trying to convert a DataGridView cell to a control:
Control dat = new Control(); dat = Convert.ChangeType(dataGridView1[colIndex,rowIndex], typeof(Control));
I am fetching the values of colIndex and rowIndes from a index code. The problem is even though I tried many codes to convert, it does not work.
The exception I am getting is:
Can not implicitly convert an object to a control. An explicit convertion exist(are u missing a cast?)