Yavuz Selim
Yavuz Selim

Reputation: 546

Edit dataGridView cell on C#

I tried to change value of cell in DataGridView on c#. I even cannot write a "Hello" in cell. Where is the error. What is missing part?

When I click the button, nothing changes. No error, no changes.

private void button1_Click(object sender, EventArgs e)
{
    dataGridView1.ReadOnly = false;
    dataGridView1.BeginEdit(true);
    dataGridView1.Rows[0].Cells[0].Value = "Hello";
    dataGridView1[1, 1].Value = "Hello";
}

Upvotes: 3

Views: 24521

Answers (2)

Samuel Gitta
Samuel Gitta

Reputation: 1

One of the ways o editing a cell value is simply to assign a string to its value property.

E.g.: If the data grid is named grdStock, the current cell can be edited as below:

grdStock.CurrentCell.Value = "100";

The above works if you have selected the cell to edit.

There is however a situation when you need to edit a referenced cell, i.e. when you tell the program to locate the cell to edit by its cell reference.

For example:

grdStock[1, grdStock.CurrentCell.RowIndex].Value = "BCS001";
grdStock[2, grdStock.CurrentCell.RowIndex].Value = "Cashew Nuts";

The above will work in the selected row and you know the columns to edit. This will definitely edit the cells. NOTE however that if your grid is bound to the data, you might need some way to save the data as well. I have not addressed this option to write back to the data source automatically because I personally do not use bound controls. But for purposes of editing the grid, this works perfectly.

I hope that helps,

Samuel

Upvotes: 0

Joel
Joel

Reputation: 7569

Well, not sure if this helps, but try this:

  • The underlying data source supports editing.
  • The DataGridView control is enabled.
  • The EditMode property value is not EditProgrammatically.
  • The ReadOnly properties of the cell, row, column, and control are all set to false.

Taken from MSDN.

Upvotes: 2

Related Questions