Can someone please post a code in c# to create a Textbox inside a datagridview and which should have events like text_changed, enter , keydown events . i Have created a customcontrol datagridview for this as it will be used multiple times but dont know how to declare a textbox inside it .
public partial class CustomControl1 : DataGridView
{
public CustomControl1()
{
InitializeComponent();
}
The DataGridView
already creates a control for the purpose of editing a cell in most cases. There are no controls in the grid by default, which makes performance better, and a cell entering edit mode is literally a control being created and embedded in the cell. The type of the control depends on the type of the cell, which generally depends on the type of the column. For most data, the DataGridViewTextBoxColumn
is the default, so every editing control will be a TextBox
.
When a cell enters edit mode, the DataGridView
raises the EditingControlShowing
event. You can access the editing control there and treat it like you would any other control, including handling its events. It's important that you detach any event handlers you added, which you can do in the CellEndEdit
event handler. Here's an example of handling the TextChanged
event of the editing control:
private TextBox editingControl;
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
editingControl = (TextBox)e.Control;
editingControl.TextChanged += EditingControl_TextChanged;
}
private void EditingControl_TextChanged(object sender, EventArgs e)
{
// ...
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (editingControl != null)
{
editingControl.TextChanged -= EditingControl_TextChanged;
editingControl = null;
}
}