I solve this to myself by copying the code inside the EventHandler to an other function, let's say
SomeFunction
. Then, inside my EventHandler I call code>SomeFuntion and you can call
SomeFunction
anywhere you'd like. In this way, you are still executing the same code as the EventHandler.
An example:
This is the first code of an EventHandler:
private void btnSearch_Click(object sender, EventArgs e)
{
int rowIndex = -1;
bool found = false;
dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
int searchValue = int.Parse(tbSearchValue.Text);
foreach (DataGridViewRow row in dgvProjects.Rows)
{
int compareValue = int.Parse(row.Cells[2].Value.ToString());
if (compareValue.Equals(searchValue))
{
found = true;
rowIndex = row.Index;
dgvProjects.Rows[row.Index].Selected = true;
dgvProjects.FirstDisplayedScrollingRowIndex = rowIndex;
break;
}
}
if (!found)
MessageBox.Show("Project number not found.\n\nBe sure you're searching for the right project number.", "Project not found",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
catch (FormatException)
{
MessageBox.Show("Your input is not a number.", "Input Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Now I want to call this code in an other function (In my example an other EventHandler, but it's the same idea). So I copy this code to a new function:
private void SearchProject()
{
int rowIndex = -1;
bool found = false;
dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
int searchValue = int.Parse(tbSearchValue.Text);
foreach (DataGridViewRow row in dgvProjects.Rows)
{
int compareValue = int.Parse(row.Cells[2].Value.ToString());
if (compareValue.Equals(searchValue))
{
found = true;
rowIndex = row.Index;
dgvProjects.Rows[row.Index].Selected = true;
dgvProjects.FirstDisplayedScrollingRowIndex = rowIndex;
break;
}
}
if (!found)
MessageBox.Show("Project number not found.\n\nBe sure you're searching for the right project number.", "Project not found",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
catch (FormatException)
{
MessageBox.Show("Your input is not a number.", "Input Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Then I change my previous EventHandler code to:
private void btnSearch_Click(object sender, EventArgs e)
{
SearchProject();
}
And now I can call
SearchProject()
in an other function too:
private void tbSearchValue_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
SearchProject();
}