当我按Enter键时,dataGridView获取更新单元格的值

时间:2018-01-23 13:12:35

标签: c# visual-studio datagridview

我是视觉工作室中Windows窗体和c#的初学者。现在,我正在做一个软件,其中使用了dataGridView元素。在那里,有五列(见图),其中四列是只读的,其中一列(Column2)可由用户修改(输入文本)。行数由用户在外部xml文件中定义。同样是第1列和第3-5列中的数据。

enter image description here

当表中的数据更新时,第2列为空,用户应引入一些值。引入每个值的顺序,它是不相关的。但是,单元格中修改的值应自动保存在变量中,以便稍后与column3和column4的值进行比较。例如,如果我在column2中给出值1,2,则应该表示一个消息框范围之间的值否则值不正确。

enter image description here

我正在寻找正确的事件,当我按Enter键时,我可以将值保存到变量中。我尝试用以下事件进行一些试验

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
    {
        //var selectedcell = dataGridView1.CurrentCell.Value;
        //Console.Write(selectedcell);
        string msg = String.Format("Row: {0}, Column: {1}",
    dataGridView1.CurrentCell.RowIndex,
    dataGridView1.CurrentCell.ColumnIndex);
        MessageBox.Show(msg, "Current Cell");

    }

 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        //var item = dataGridView1.Rows[e.RowIndex].Cells[1].Value;
        //MessageBox.Show(item.)
    }

    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
    //    var row = dataGridView1.Rows[e.RowIndex];
    //    var changedValue = (string)row.Cells[e.ColumnIndex].Value;
    //   Console.Write(changedValue);
    }

不幸的是,现在没有任何作用。我对如何实现它没有任何想法。

1 个答案:

答案 0 :(得分:0)

试试这个:

private void dataGridView1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    if (e.KeyChar == (char)13)
    {
        var column2Value = dataGridView1.GetFocusedRowCellValue(dataGridView1.Columns[1]);
        MessageBox.Show(column2Value.ToString())
    }        
}