I have developed a customDataGridView for my project. In its OnEnter event , i have tried to set the first cell of first row and first column in editable mode as soon as it gets focus . It is declared as follows.
public partial class CustomControl1 : DataGridView
{
public CustomControl1()
{
this.KeyDown += new KeyEventHandler(CustomDataGridView_KeyDown);
InitializeComponent();
}
protected override void OnEnter(EventArgs e)
{
base.OnEnter(e);
this.CurrentCell = this.Rows[0].Cells[0];
this.BeginEdit(true);
}
now the problem is that when I run the debugger, I found out that the code in OnEnter is running twice. what I mean is when the debugger hits
customControl11.Focus();
on form2.cs, it calls the onenter event of customdatagridview ,which first selects the first cell of first row and first column and then set that cell in editable mode by when it hits
this.BeginEdit(true);
. which in turn calls the
customControl11_EditingControlShowing
Till here everything Ok . but now what happens is when it finishes the code block of
customControl11_EditingControlShowing
, it again goes to the OnEnter event of the customcontrol1 and runs the code block again
I can't understand the logic behind it. If any respected member catches my error, please suggest the way to stop it.
What I have tried:
public partial class Form2 : Form
{
private DataSet dataSet;
private DataView dataView;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
customControl11.Columns[3].ReadOnly = true;
dataGridView1.Visible = false;
dataGridView1.AllowUserToAddRows = false;
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data Source =DESKTOP-197P3FU\\SQLEXPRESS;Integrated security=SSPI;database=Tally";
SqlDataAdapter adapter = new SqlDataAdapter($"SELECT * FROM ledgernames", conn);
dataSet = new DataSet();
adapter.Fill(dataSet);
}
dataGridView1.DataSource = dataSet.Tables[0];
}
private void customtextbox3_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
<pre> case Keys.Enter:
{
if (dataGridView1.Rows.Count > 0)
{
dataGridView1.Visible = false;
customtextbox3.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
customControl11.Focus();
dataView.RowFilter = "";
}
e.Handled = e.SuppressKeyPress = true;
break;
}
}
}
}
private void customControl11_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (customControl11.CurrentCell.ColumnIndex == 0)
{
TextBox textBox = e.Control as TextBox;
if (textBox != null)
{
textBox.TextChanged -= TextBox_TextChanged;
textBox.KeyDown -= TextBox_KeyDown;
textBox.Enter -= TextBox_Enter;
textBox.TextChanged += TextBox_TextChanged;
textBox.KeyDown += TextBox_KeyDown;
textBox.Enter += TextBox_Enter;
}
}
}