提问人:Nisha Goel 提问时间:7/2/2023 最后编辑:Stefan WuebbeNisha Goel 更新时间:7/3/2023 访问量:54
输入键作为选项卡在 datagridview 中无法正常工作
Enter key as tab not working properly in datagridview
问:
我创建了一个自定义 DataGridView,并在按 Enter 键时尝试将我的单元格向右移动(而不是在按 Enter 键时向下移动),但我发现我必须按两次 Enter 才能向右移动。当我第一次按回车键时,它仍然向下(默认方式),然后如果我再次按回车键,它就会向右移动。
public partial class Paymentdatagridview : DataGridView
{
public Paymentdatagridview()
{
// i have set enableheadervisualstyles to false
// make bold the headers
// Add the columns to your custom DataGridView
DataGridViewColumn column1 = new DataGridViewTextBoxColumn();
column1.Name = "Column1";
column1.HeaderText = "Particulars";
column1.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
column1.SortMode = DataGridViewColumnSortMode.Automatic;
this.Columns.Add(column1);
DataGridViewColumn column2 = new DataGridViewTextBoxColumn();
column2.Name = "Column2";
column2.HeaderText = "Amount";
column2.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
column2.SortMode = DataGridViewColumnSortMode.Programmatic;
this.Columns.Add(column2);
this.AllowUserToAddRows = true;
this.RowHeadersVisible = false;
this.ColumnHeadersDefaultCellStyle.Font = new Font("Tahoma", 9.75F, FontStyle.Bold);
this.CellBorderStyle = DataGridViewCellBorderStyle.None;
InitializeComponent();
}
protected override void OnEnter(EventArgs e)
{
// Set the current cell to the first cell and enable editing when the control receives focus
if (RowCount > 0 && ColumnCount > 0)
{
CurrentCell = Rows[0].Cells[0];
BeginEdit(true);
}
base.OnEnter(e);
}
protected override bool ProcessDataGridViewKey(KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// Move the focus to the next column and row when Enter key is pressed
if (CurrentCell.ColumnIndex == ColumnCount - 1)
{
if (CurrentCell.RowIndex == RowCount - 1)
{
// Reached the last cell, move focus to the first cell
CurrentCell = Rows[0].Cells[0];
}
else
{
// Move to the first cell of the next row
CurrentCell = Rows[CurrentCell.RowIndex + 1].Cells[0];
}
}
else
{
// Move to the next column
CurrentCell = Rows[CurrentCell.RowIndex].Cells[CurrentCell.ColumnIndex + 1];
}
BeginEdit(true);
e.Handled = true;
return true;
}
return base.ProcessDataGridViewKey(e);
}
}
答:
0赞
rotabor
7/2/2023
#1
您需要知道在单元格中输入值并向右移动的键已经可用。这个键是 Tab。这或多或少是标准的。只需使用 Tab,不要浪费您的时间。
尽管如此,如果您想要更改默认值,只需将“Keys.Enter”替换为“Keys.Tab”(处理 KeyDown 和 KeyPress 事件)。或者尝试在窗体级别捕获键,如果 DatagridView 处于焦点中,则将 Enter 替换为 Tab。
评论