C# 为什么要跳过行?

C# 为什么要跳过行?,c#,winforms,datagridview,datagridviewtextboxcell,C#,Winforms,Datagridview,Datagridviewtextboxcell,我用这种方式填充了一个DataGridView:偶数行包含用户不可编辑的“常量”值。奇数行可以由用户编辑,但只能包含0或1个字符。如果单元格包含一个值,并且用户按下一个键,它应该首先向下移动到下一个单元格,然后允许在下一个单元格中输入该值。通过这种方式,用户可以继续按键,并且每次都会填充下面的单元格 我得到了以下代码(基于David Hall的代码:): 当我第一次在一个已经有值的单元格中输入val时,这种方法非常有效——它会向下移动到下一个单元格,然后按下键在那里输入值。然而,在那之后,它每次

我用这种方式填充了一个DataGridView:偶数行包含用户不可编辑的“常量”值。奇数行可以由用户编辑,但只能包含0或1个字符。如果单元格包含一个值,并且用户按下一个键,它应该首先向下移动到下一个单元格,然后允许在下一个单元格中输入该值。通过这种方式,用户可以继续按键,并且每次都会填充下面的单元格

我得到了以下代码(基于David Hall的代码:):

当我第一次在一个已经有值的单元格中输入val时,这种方法非常有效——它会向下移动到下一个单元格,然后按下键在那里输入值。然而,在那之后,它每次跳过一个以上的单元格。注意,如果我首先在第5列第2行的单元格中输入“2”,它将移动到第3行(好!);然后,它移到第5行,跳过第4行。在下一次按键时,它移动到第8行,跳过第6行和第7行,依此类推

为什么会这样,解决办法是什么

更新 好的,根据LarsTech下面的回答,我现在得到了以下代码:

private void dataGridViewPlatypus_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) {
    int columnIndex = (((DataGridView)(sender)).CurrentCell.ColumnIndex);
    if (columnIndex % 2 == 1) {
        e.Control.KeyPress -= TextboxNumeric_KeyPress;
        e.Control.KeyPress += TextboxNumeric_KeyPress;
    }
}

private void TextboxNumeric_KeyPress(object sender, KeyPressEventArgs e) {
    const int LAST_ROW = 11;
    const int LAST_COL = 15;
    TextBox tb = sender as TextBox;
    if (tb.TextLength >= 1) {
        if (dataGridViewPlatypus.CurrentCell.RowIndex != LAST_ROW) {
            dataGridViewPlatypus.CurrentCell = dataGridViewPlatypus[
                dataGridViewPlatypus.CurrentCell.ColumnIndex,
                dataGridViewPlatypus.CurrentCell.RowIndex + 1];
        } else { // on last row
            if (dataGridViewPlatypus.CurrentCell.ColumnIndex != LAST_COL) {
                dataGridViewPlatypus.CurrentCell =
                    dataGridViewPlatypus[dataGridViewPlatypus.CurrentCell.ColumnIndex + 2, 0];
            } else // on last row AND last editable column
            {
                dataGridViewPlatypus.CurrentCell = dataGridViewPlatypus[1, 0];
            }
        }
    }
}

但是,现在的问题是,如果我所在的单元格中输入了以前的值,它将不会用输入的新值覆盖旧值。那么,有没有一种方法可以在允许新值替换单元格中现有值的同时不在此单元格中输入其他值?

您正在添加越来越多的按键事件:

e.Control.KeyPress += TextboxNumeric_KeyPress;
不删除以前的按键事件。所以它多次调用它

尝试将其更改为以下内容:

if (columnIndex % 2 == 1) {
  e.Control.KeyPress -= TextboxNumeric_KeyPress;
  e.Control.KeyPress += TextboxNumeric_KeyPress;
}

您正在添加越来越多的按键事件:

e.Control.KeyPress += TextboxNumeric_KeyPress;
不删除以前的按键事件。所以它多次调用它

尝试将其更改为以下内容:

if (columnIndex % 2 == 1) {
  e.Control.KeyPress -= TextboxNumeric_KeyPress;
  e.Control.KeyPress += TextboxNumeric_KeyPress;
}

好的,我解决了我的问题,从KeyPress改为KeyUp:private void TextboxNumeric_KeyUp(object sender,KeyEventArgs e){…然后识别输入的新val。好的,我解决了我的问题,从KeyPress改为KeyUp:private void TextboxNumeric_KeyUp(object sender,KeyEventArgs e){…然后识别输入的新val。