移动DataGridView所选单元格/行向上/向下按键按下使用C#

时间:2016-06-22 13:35:49

标签: c# .net datagridview keypress

我的表单中有datagridview1,其中有一列,使用以下代码隐藏其标题的行数不受限制...

dataGridView1.RowHeadersVisible = false;   // Hide Row Header
dataGridView1.ColumnHeadersVisible = false; // Hide Column Header

所以现在当我们专注于它时,第一行已被选中并突出显示。现在我想使用我的键盘向上和向下键使用下面的KeyDown函数上下移动我的选择,当我按下ENTER时,选择单元格值应该转到类级变量,默认情况下首先是焦点行/ cell值也应设置为类级变量...

private void datagridview1_KeyDown(object sender, KeyEventArgs e)
{
   if (dataGridView1.Visible == true)
   {
       if (e.KeyCode.Equals(Keys.Up))
       {
           MessageBox.Show("Move UP Row/Cell And Select It");
       }
       if (e.KeyCode.Equals(Keys.Down))
       {
           MessageBox.Show("Move Down Row/Cell And Select It");
       }
       if (e.KeyCode.Equals(Keys.Enter))
       {
           MessageBox.Show("Send Selected Cell Value To Class Level Variable");
       }
       e.Handled = true;
    }
 }

目前我有一些包含datagridview CELL值的类级别变量,我使用下面的代码获取CellClick但是我想使用高级代码在键上执行此功能...

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    value = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
}

我的班级变量就像......

public partial class Form1: Form
{
    string value = "";
    public MainForm()
    {
        InitializeComponent();
    }
}

那我怎么能用C#...... ???

来做

更新:

对于UP / DOWN选择,我使用了以下代码及其工作原理。那么现在如何按ENTER键将所选单元格值发送到类级变量...... ???

private void selectUpRow()
{
    DataGridView dgv = dataGridView1;
    int totalRows = dgv.Rows.Count;
    int rowIndex = dgv.SelectedCells[0].OwningRow.Index;
    if (rowIndex == 0)
        return;
    int colIndex = dgv.SelectedCells[0].OwningColumn.Index;
    DataGridViewRow selectedRow = dgv.Rows[rowIndex];
    dgv.ClearSelection();
    dgv.Rows[rowIndex - 1].Cells[colIndex].Selected = true;
}

private void selectDownRow()
{
    DataGridView dgv = dataGridView1;
    int totalRows = dgv.Rows.Count;
    int rowIndex = dgv.SelectedCells[0].OwningRow.Index;
    if (rowIndex == totalRows - 1)
        return;
    int colIndex = dgv.SelectedCells[0].OwningColumn.Index;
    DataGridViewRow selectedRow = dgv.Rows[rowIndex];
    dgv.ClearSelection();
    dgv.Rows[rowIndex + 1].Cells[colIndex].Selected = true;
}

1 个答案:

答案 0 :(得分:0)

所以最后我通过尝试Bla Bla Bla来实现它。以下是代码的简短答案......

public void SearchFunc()
{
    cursorPos = 0;
    docReadCount = 0;

    flag:

    for (int i = cursorPos; i < docEndPos; i++)
    {

        if (i + 1 == docEndPos|| i == docEndPos)
        {
            if(docReadCount == 1) return;
            cursorPos = 0;
            docReadCount++;
            goto flag;
        }

        if (doc.Range(i, i+ 1).Text == "@" || 
            doc.Range(i, i+ 1).Text == "&" || 
            doc.Range(i, i+ 1).Text == "*")
        {
            //do something
        }
    }
}