この方法で入力した DataGridView があります。偶数行には、ユーザーが編集できない「定数」値が含まれています。奇数行はユーザーが編集できますが、0 または 1 文字のみを含める必要があります。セルに値が含まれているときにユーザーがキーを押すと、最初に次のセルに移動してから、その値をその次のセルに入力できるようにする必要があります。このようにして、ユーザーはキーを押し続けることができ、そのたびに下のセルが入力されます。
私はこのコードを持っています (David Hall のコードに基づいています: How can I move programmatically move from one cell in a datagridview to another? ):
private void dataGridViewPlatypus_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
int columnIndex = (((DataGridView)(sender)).CurrentCell.ColumnIndex);
if (columnIndex % 2 == 1) {
e.Control.KeyPress += TextboxNumeric_KeyPress;
}
}
private void TextboxNumeric_KeyPress(object sender, KeyPressEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb.TextLength >= 1)
{
dataGridViewPlatypus.CurrentCell = dataGridViewPlatypus[
dataGridViewPlatypus.CurrentCell.ColumnIndex,
dataGridViewPlatypus.CurrentCell.RowIndex + 1];
}
}
これは、既に値があるセルに最初に val を入力したときにうまく機能します。次のセルに移動し、その後のキーを押すとそこに値が入力されます。ただし、その後は、毎回もう 1 つのセルをスキップします。IOW、最初に列 5、行 2 のセルに「2」を入力すると、行 3 に移動します (良い!)。次に、行 4 をスキップして行 5 に移動します。次にキーを押すと、行 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];
}
}
}
}
ただし、問題は、以前の値が入力されたセルにいる場合、入力された新しい値で古い値が上書きされないことです。このセルに別の値を入力しないと同時に、セル内の既存の値を新しい値で置き換えることを許可する方法はありますか?