简体   繁体   中英

Keydown event being swallowed/not actioned in DataGridView control

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?

I've had very little response to this question on this forum and others. It must be a very difficult problem, or I'm simply expecting too much from the DataGridView control. After many hours of trial and error, I have settled on a solution which does not require subclassing. The solution is not exactly what I wanted, ie to prevent another another row from being appended to the bottom of the grid once the user begins typing into the newly added row, but it comes close. I use the CellLeave event to turn off AllowUserToAddRows . When the user presses Tab or Enter to enter the data into the 1st cell, this effectively removes the newly added row from the grid leaving the user in the next cell of the newly added (last) row of the grid (without an empty row underneath). Not elegant, but at least mostly functional. Here's the code:

private void uxContactEmailAddressesGrd_CellLeave(object sender, DataGridViewCellEventArgs e)
{
    uxContactEmailAddressesGrd.AllowUserToAddRows = false;
}

Maybe one day someone else will come across this problem and find a solution more elegant than mine. That'd be great. Make sure you post your solution to this site for others to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM