简体   繁体   English

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

[英]dataGridView get the value of an updated cell when I press enter

I'm a beginner with windows forms and c# in visual studio.我是 Visual Studio 中 windows 窗体和 c# 的初学者。 Right now, I'm doing a software, where a dataGridView element is used.现在,我正在做一个软件,其中使用了 dataGridView 元素。 In there, there is five columns (see Picture), four of them are Read-only and one of them (Column2) can the user modify it (Input Text).在那里,有五列(见图),其中四列是只读的,其中一列(Column2)可以由用户修改(输入文本)。 The number of rows are defined by the user in an external xml file.行数由用户在外部 xml 文件中定义。 Likewise the data in the Columns 1 and 3-5.同样,第 1 列和第 3-5 列中的数据。

在此处输入图片说明

When the data is updated in the table, the column 2 is empty and some values should be introduced by the user.当表中的数据更新时,第2列为空,一些值应由用户引入。 The order in which each value is introduced, it is not relevant.每个值的引入顺序无关紧要。 However, the value modified in the cell should be saved automatically in a variable in order to be compared later with the values of the column3 and column 4. For example if I give the value 1,2 in the column2 a Message box should be said value between the range otherwise value incorrect.但是,单元格中修改的值应自动保存在变量中,以便稍后与 column3 和 column 4 的值进行比较。例如,如果我在 column2 中给出值 1,2,则应显示消息框范围之间的值,否则值不正确。

在此处输入图片说明

I was looking the right event where I can save the value into variable when I press enter.我正在寻找正确的事件,当我按下 Enter 键时,我可以将值保存到变量中。 I tried making some trials with the following events我尝试对以下事件进行一些试验

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);
    }

Unfortunatelly, nothing works right now.不幸的是,现在没有任何效果。 I don't have any ideas how to implement it.我没有任何想法如何实现它。

Try this :试试这个:

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())
    }        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM