Datagridview enter键从下一行选择下一个单元格

时间:2016-12-11 08:05:13

标签: c# .net winforms datagridview

该代码仅在我第一次添加值时才有效。 问题是,当我回到之前添加的值并且我点击输入时,它会从下一行选择下一个单元格,而不是下一个右侧单元格。

这是我的代码:

>>> 104.445 - 104.44
0.0049999999999954525
>>> 104.445 - 104.44 + 104.44
104.445

1 个答案:

答案 0 :(得分:0)

完全改变了方法。使用 DataGridView 创建了一个新类扩展并覆盖了两个函数。 OnKeyDown ProcessDialogKey

以下是代码:

conn.Open();

SqlDataAdapter sda = new SqlDataAdapter("Update [Table] Set [Name]='" + textBox2.Text + "',[Course]='" + comboBox1.Text + "',[YearSection]='" + textBox3.Text + "' Where [Id]='"+textBox1.Text+"')", conn);

sda.SelectCommand.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Updated Successfully !!!");

添加此类后,您可以构建项目,然后您可以从工具箱> DgvDemoComponents> CustomDataGridview 中选择此新控件 或者,如果要将旧的DataGridView转换为新的DataGridView,只需更改为以下行:

class CustomDataGridview : DataGridView
{
    protected override bool ProcessDialogKey(Keys keyData) // Fired when key is press in edit mode
    {
        if (keyData == Keys.Enter)
        {
            MoveToRightCell();
            return true;
        }
        return base.ProcessDialogKey(keyData);
    }
    protected override void OnKeyDown(KeyEventArgs e) // Fired when key is press in non-edit mode
    {
        if (e.KeyData == Keys.Enter)
        {
            MoveToRightCell();
            e.Handled = true;
            return;
        }
        base.OnKeyDown(e);
    }
    private void MoveToRightCell()
    {
        int col = this.CurrentCell.ColumnIndex;
        int row = this.CurrentCell.RowIndex;
        if (col < this.ColumnCount - 1)
        {
            col++;
        }
        else
        {
            col = 0;
            row++;
        }
        if (row == this.RowCount)
        {
            this.Rows.Add();
        }
        this.CurrentCell = this[col, row];
    }
}

this.dataGridView1 = new System.Windows.Forms.DataGridView();

第二种方法会导致设计师遇到一些问题,只需选择忽略并继续。

相关问题