简体   繁体   中英

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

I'm a beginner with windows forms and c# in visual studio. Right now, I'm doing a software, where a dataGridView element is used. 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). The number of rows are defined by the user in an external xml file. Likewise the data in the Columns 1 and 3-5.

在此处输入图片说明

When the data is updated in the table, the column 2 is empty and some values should be introduced by the user. 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.

在此处输入图片说明

I was looking the right event where I can save the value into variable when I press 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())
    }        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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