How to programmatically set cell value in DataGridView?
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
Change DataGridView Cell Value Programmatically
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";
}
}
Add cell value after set datasource of datagridview
Try this..
if (row.Index != 0)
{
//replace RowObject with the name of your underlying class that constitutes each
//row
RowObject obj = (RowObject)row.DataBoundItem;
//replace DiscountProperty and TaxProperty with the names of the properties on
//your RowObject that correspond to these values
obj.DiscountProperty = "10";
obj.TaxProperty = "10";
}
Hopefully this will work for you. Here is a link to a similar question that elaborates more on why you should update the data this way when modifying a DataGridView with an underlying DataSource. Programmatically set cell value in data grid view
Change datagridview cell value in edit mode
When the cell is in edit mode you need to change the text in the edit control, usually a Textbox. You can get (and hold) a handle to it in the EditingControlShowing
event:
TextBox editBox = null;
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is TextBox) editBox = e.Control as TextBox;
}
But using the CellEnter
event is not a good idea as it will be called when scrolling or clicking around as well..
To catch the beginning of editing you use the BeginEdit
event:
int yourEditColumn = 5;
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if (e.ColumnIndex == yourEditColumn )
{
string yourValue = "12345";
dataGridView1.Rows[e.RowIndex].Cells[yourEditColumn ].Value = yourValue;
if (editBox != null) editBox.Text = yourValue;
}
}
Change value in DataGridView directly
You can simply do this (assuming that you want to change one value programmatically):
dataGridView1.Rows[RowNumber].Cells[CC.Index].Value = newValue;
And how to enable editing of certain cell was already explained here.
How to dynamically assign Datagridview cell values based on data from my database?
I would do this on the DataBindingComplete event:
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
foreach (DataGridViewRow r in dataGridView1.Rows)
{
if (r.Cells["status"].Value.ToString() == "Online")
{
//add image here
}
}
}
Your datagrid would need to attach to the DataBindingComplete
as well
This answer might also be useful:
https://stackoverflow.com/a/8182203/2589202
How to set Cell value of DataGridViewRow by column name?
So in order to accomplish the approach you desire it would need to be done this way:
//Create the new row first and get the index of the new row
int rowIndex = this.dataGridView1.Rows.Add();
//Obtain a reference to the newly created DataGridViewRow
var row = this.dataGridView1.Rows[rowIndex];
//Now this won't fail since the row and columns exist
row.Cells["code"].Value = product.Id;
row.Cells["description"].Value = product.Description;
How to add a Cell programmatically to a DataGridView?
Two ways:
- You need to have a
Column
first, then you can replace anyCell
in theColumn
by whatever type ofCell
you want to create:
DataGridViewTextBoxColumn normalColumn = new DataGridViewTextBoxColumn();
DGV_Points.Columns.Insert(yourColumnIndex, normalColumn);
DGV_Points.Rows.Add(11); // we need at least one row where we can insert a cell
DataGridViewComboBoxCell aCell = new DataGridViewComboBoxCell();
DGV_Points.Rows[someRowIndex].Cells[yourColumnIndex] = aCell;
- Or you create that
Column
to have theColumnType
you want and allCells
in theColumn
will have the rightType
from the beginning:
DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
comboCol.HeaderText = "yourHeaderText";
DGV_Points.Columns.Insert(yourColumnIndex, comboCol);
Note that the first method creates only as many DataGridViewComboBoxCells
as you make it to whereas the second way immediatly create a DataGridViewComboBoxCell
in each Row
. It is up to you to decide what you want..
Instead or Inserting
at a given position you may want to simply Add
the Column
. The Add
method returns the Index
of the new Column
.
Since we are adding a DataGridViewComboBoxCells
here is an example how you can fill the Items
of the new dropdown cell:
List<string> items1 = new List<string> (){ "111", "222", "333", "444", "555" };
((DataGridViewComboBoxCell)DGV_Points.Rows[2].Cells[0] ).Items
.AddRange(items1.ToArray());
DGV_Points.Rows[2].Cells[0].Value = "222";
This fills the dropdownlist of the cell in row 2, column 0 with five string values and select the value to be "222". Note that this way you must fill the Items
of each Cell
and you can fill each one with a different list of values to choose from.
You can also set an individual Cell's DataSource
: aCell.DataSource = items1;
or you can set it for the Column
: comboCol.DataSource = items1;
Related Topics
Mvvm in Wpf - How to Alert Viewmodel of Changes in Model... or Should I
Convert Linq Query Result to Dictionary
How to Fix Error: "Could Not Find Schema Information for the Attribute/Element" by Creating Schema
Auto Create Database in Entity Framework Core
Jcontainer, Jobject, Jtoken and Linq Confusion
What's the Difference Between Anonymous Methods (C# 2.0) and Lambda Expressions (C# 3.0)
Catch All Unhandled Exceptions in ASP.NET Web API
Should I Always Return Ienumerable<T> Instead of Ilist<T>
C# Entity-Framework: How to Combine a .Find and .Include on a Model Object
Simple Animation Using C#/Windows Forms
.Net Timezoneinfo from Olson Time Zone
Enable Entity Framework 6 for MySQL (C#) in Winforms of Microsoft Visual Studio 2013
How to Pronounce "=>" as Used in Lambda Expressions in .Net
Generate a Self-Signed Certificate on the Fly