I have a problem with some code I developed based on the article DataGridView keydown event not working in C#.
I wanted to allow the user to add a row to a Dataviewgrid control, but found that by enabling AllowUserToAddRows
this caused an additional row to be shown as soon as the first character was typed into the new cell in the new row. This would have been confusing to my poor user, so to prevent this, I used the code from above article to immediately disable AllowUserToAddRows
at every keystroke (although would have preferred to only do it after the first char was typed). However, this seems to swallow the 1st char typed, i,.e. it is not passed onto the base class for processing. Here's the full code:
public sealed class XDataGridView : DataGridView
{
private bool _singleUpdateOnly = true;
public bool SingleUpdateOnly
{
get { return _singleUpdateOnly; }
set { _singleUpdateOnly = value; }
}
[Description("Disallows user adding rows as soon as a key is struck to ensure no blank row at bottom of grid")]
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
{
if (SingleUpdateOnly)
{
AllowUserToAddRows = false;
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
Why is the 1st char I type swallowed? How can I prevent this from happening? Is there a better way than what I have coded?