日期:2014-05-18  浏览次数:21155 次

C#2005winForm的DataGridView中,在输入时怎样控制的光标移动问题
假如DataGridView中有5列,现在是想在第一列中输入完成后敲enter键后,直接到该行的下一列,而不是进入下一行的该一列,当输入到该行的最后一列时,直接进入
下一行的第一列,请问怎样控制?


------解决方案--------------------
重写DataGridView并参考如下的代码,使程序里的DataGridView都使用这个新的类就可以了。

class dataGridViewEx : DataGridView
{
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Return && this.EndEdit())
{
if (this.CurrentCell.ColumnIndex + 1 < this.ColumnCount)
{
this.CurrentCell = this[this.CurrentCell.ColumnIndex + 1, this.CurrentCell.RowIndex];
}
else
{
if (this.CurrentCell.RowIndex < this.Rows.Count)
{
this.CurrentCell = this[0, this.CurrentCell.RowIndex + 1];
}
else
{
this.CurrentCell = this[0, 0];
}
}
return true;
}
return base.ProcessDialogKey(keyData);
}
protected override bool ProcessDataGridViewKey(KeyEventArgs e)
{
if (e.KeyData == Keys.Return && this.EndEdit())
{
if (this.CurrentCell.ColumnIndex + 1 < this.ColumnCount)
{
this.CurrentCell = this[this.CurrentCell.ColumnIndex + 1, this.CurrentCell.RowIndex];
}
else
{
if (this.CurrentCell.RowIndex < this.Rows.Count)
{
this.CurrentCell = this[0, this.CurrentCell.RowIndex + 1];
}
else
{
this.CurrentCell = this[0, 0];
}
}
return true;
}
return base.ProcessDataGridViewKey(e);
}
}

------解决方案--------------------
int column = dataGridViewX2.CurrentCell.OwningColumn.Index + 1;
if (column < dataGridViewX2.ColumnCount)
{
if (column > this.dataGridViewX2.ColumnCount)
column = 0;
this.dataGridViewX2.CurrentCell = this.dataGridViewX2[column, dataGridViewX2.CurrentRow.Index];
}
else
{
int row = this.dataGridViewX2.CurrentRow.Index + 1;
if (row > this.dataGridViewX2.RowCount - 1)
row = 0;
this.dataGridViewX2.CurrentCell = this.dataGridViewX2[0, row];
}
我自己试的,,应该可以满足楼主的需要。初学者,希望能给楼主点帮助。