How to programmatically set cell value in DataGridView?
Solution 1:
If the DataGridView
is databound, you shouldn't directly modify the content of the cell. Instead, you should modify the databound object. You can access that object through the DataBoundItem
of the DataGridViewRow
:
MyObject obj = (MyObject)dataGridView.CurrentRow.DataBoundItem;
obj.MyProperty = newValue;
Note that the bound object should implement INotifyPropertyChanged
so that the change is reflected in the DataGridView
Solution 2:
dataGridView1[1,1].Value="tes";
Solution 3:
If you don't want to modify the databound object from some reason (for example you want to show some view in your grid, but you don't want it as a part of the datasource object), you might want to do this:
1.Add column manually:
DataGridViewColumn c = new DataGridViewColumn();
DataGridViewCell cell = new DataGridViewTextBoxCell();
c.CellTemplate = cell;
c.HeaderText = "added";
c.Name = "added";
c.Visible = true;
dgv.Columns.Insert(0, c);
2.In the DataBindingComplete event do something like this:
foreach (DataGridViewRow row in dgv.Rows)
{if (row.Cells[7].Value.ToString()=="1")
row.Cells[0].Value = "number one"; }
(just a stupid example)
but remember IT HAS to be in the DataBindingComplete, otherwise value will remain blank
Solution 4:
I searched for the solution how I can insert a new row and How to set the individual values of the cells inside it like Excel. I solved with following code:
dataGridView1.ReadOnly = false; //Before modifying, it is required.
dataGridView1.Rows.Add(); //Inserting first row if yet there is no row, first row number is '0'
dataGridView1.Rows[0].Cells[0].Value = "Razib, this is 0,0!"; //Setting the leftmost and topmost cell's value (Not the column header row!)
dataGridView1[1, 0].Value = "This is 0,1!"; //Setting the Second cell of the first row!
Note:
- Previously I have designed the columns in design mode.
- I have set the row header visibility to false from property of the datagridview.
- The last line is important to understand: When yoou directly giving index of datagridview, the first number is cell number, second one is row number! Remember it!
Hope this might help you.