views:

439

answers:

2

I am trying to support editing multiple cells on a datagridview. I am nearly complete, as it correctly copies the contents to other cells when the editing is done. What I am working on now is capturing the first key pressed.

When I am editing just one cell, using EditOnKeystrokeOrF2 works fine. However, when multiple cells are selected, I am capturing the Keydown event and manually calling BeginEdit. When I do that, however, the pressed key isn't included in the edit.

How can I get that first key pressed into my cell?

A: 

May be it is sufficent to mark the key as not handled.

private void dataGridView_KeyDown(Object sender, KeyEventArgs keyEventArgs)
{
   keyEventArgs.Handled = false;
}
Daniel Brückner
Ooh, thought this looked promising. But, when I tried it, it didn't help, and it looked like the "Handled" property was already false.
Andy Stampor
A: 

I did some additional experimenting and found a way to make this happen. It is a bit sloppy, but it works.

private int _keyValue;
private Boolean _checkKeyValue = false;

private void Grid1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
    DataGridViewCell cell = Grid1.Rows[e.RowIndex].Cells[e.ColumnIndex];

    if (_checkKeyValue)
    {
     _checkKeyValue = false;

     if (value != -1)
     {
      cell.Value = _keyValue;
     }
    } 
}

private void Grid1_KeyDown(object sender, KeyEventArgs e)
{
    if (Grid1.SelectedCells.Count > 1)
     {
      _checkKeyValue = true;
      _keyValue = (int)e.KeyValue;
      Grid1.BeginEdit(false);
     }
}

By registering for the CellBeginEdit event, I can plop the value in there. I do some other processing of the _keyValue to make it a number, but that isn't relevant to the rest of this.

Andy Stampor