Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change DataGridView Cell Value Programmatically

I have a datagridview which has a datatable as data source. I need to change some cell values manually. For example, if cell input value contains character 'g', it must change "abc" automatically when I leave cell. Following code checks the formatted value of current cell:

private void dgwPNotlar_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
  if (e.ColumnIndex<2||e.ColumnIndex>4||e.FormattedValue.ToString()=="")
  {
    return;
  }

  if (e.FormattedValue.ToString().Contains('G')||e.FormattedValue.ToString().Contains('g'))
  {
    dgwPNotlar.EditMode = DataGridViewEditMode.EditProgrammatically;
    dgwPNotlar.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "abc";
    dgwPNotlar.EndEdit();
    dgwPNotlar.EditMode = DataGridViewEditMode.EditOnEnter;
    return;
  }
}

When the code "dgwPNotlar.EndEdit();" runs, the cell value I changed is "abc", returns to previous value as "g" or "G"..

Any ideas?

like image 760
Sertan Pekel Avatar asked Dec 13 '13 13:12

Sertan Pekel


People also ask

How to set DataGridView cell value?

Try this way: dataGridView. CurrentCell. Value = newValue; dataGridView.

How to change DataGridView column value in c#?

Now click at any cell of DataGridView. Its value will be shown in TextBox. Update the value of the TextBox and click the "Change" button. It will replace the value of DataGridView cell value by TextBox.

How to get DataGridView cell value in c#?

You can use the DataGridViewCell. Value Property to retrieve the value stored in a particular cell. So to retrieve the value of the 'first' selected Cell and display in a MessageBox, you can: MessageBox.


1 Answers

The changing of the cell needs to happen after the validating event, so try the CellValidated event instead:

void dgv_CellValidated(object sender, DataGridViewCellEventArgs e) {
  string cellValue = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValue.ToString();
  if (cellValue.Contains('G') || cellValue.Contains('g')) {
    dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "abc";
  }
}
like image 192
LarsTech Avatar answered Sep 30 '22 06:09

LarsTech