I’m having a little trouble figuring out how to create an inherited class that extends a windows form control to always have an event handler that will handle a keypress event for each instance of that object.
I’m probably explaining this poorly. Essentially I want to extend the DatagridView class in windows forms to always have a keyPress event handler present for any instantiated object of my extended DatagridView class.
I was wondering if it’s possible to have an event handler that listens for key presses and handles them with code similar to what I have written below:
private void dgvObject_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsLetterOrDigit(e.KeyChar))
{
//start the loop at the currently selected row in the datagridview
for (int i = dgvObject.SelectedRows[0].Index; i < dgvObject.Rows.Count; i++)
{
//will only evaluate to true when the current index has iterated above above the
//selected rows index number AND the key press event argument matches the first character of the current row
// character of the
if (i > dgvObject.SelectedRows[0].Index && dgvObject.Rows[i].Cells[1].FormattedValue
.ToString().StartsWith(e.KeyChar.ToString(), true, CultureInfo.InvariantCulture))
{
//selects current iteration as the selected row
dgvObject.Rows[i].Selected = true;
//scrolls datagridview to selected row
dgvObject.FirstDisplayedScrollingRowIndex = dgvObject.SelectedRows[0].Index;
//break out of loop as I want to select the first result that matches
break;
}
}
}
}
The code above simply selects the next row that begins with the character of whatever the keypress event has in its event argument when fired. The reason I was wondering if I could have this as an inherited handler that is always present. I figured it’d be better than explicitly creating hundreds of handlers in my windows form for each individual DatagridView object. If my thinking is wrong please feel free to correct me! Anyway thanks for any input.
I’ve been programming in C# for about 5 months now, still learning as I go =)
Yes, in your inherited class just override
OnKeyPress, and you should remember to callbase.OnKeyPressafterwards: