How can i set the value of a datagrid cell using its Column and row index values? How can i set the value of a datagrid cell using its Column and row index values? wpf wpf

How can i set the value of a datagrid cell using its Column and row index values?


For a datagrid you access rows through the Items property. The cells are a collection on an item.

dataGrid2.Items[row].Cells[column].Text = "text";

This works as long as the data has been bound to the datagrid during the current page life-cycle. If this is not the case then I believe you are stuck walking the controls.


To update a WPF DataGridCell programmatically, there could be many ways...

One of the ways is to update value in the bound data item itself. This way the property change notifications will fire for all subscribed visuals including the DataGridCell itself...

Reflection approach

 var boundItem = dataGrid2.CurrentCell.Item; //// If the column is datagrid text or checkbox column var binding = ((DataGridTextColumn)dataGrid2.CurrentCell.Column).Binding; var propertyName = binding.Path.Path; var propInfo = boundItem.GetType().GetProperty(propertyName); propInfo.SetValue(boundItem, yourValue, new object[] {});

For DataGridComboBoxColumn you would have to extract the SelectedValuePath and use that in place of propertyName.

Otherways include putting cell in edit mode and updating its content value using some behavior in the EditingElementStyle... I find this cumbersome.

Do let me know if you really need that.


I used a variation based upon WPF-it's example to do the whole row and it worked!:

(sender as DataGrid).RowEditEnding -= DataGrid_RowEditEnding;foreach (var textColumn in dataGrid2.Columns.OfType<DataGridTextColumn>())            {                var binding = textColumn.Binding as Binding;                if (binding != null)                {                    var boundItem = dataGrid2.CurrentCell.Item;                    var propertyName = binding.Path.Path;                    var propInfo = boundItem.GetType().GetProperty(propertyName);                    propInfo.SetValue(boundItem, NEWVALUE, new object[] { });                }            }(sender as DataGrid).RowEditEnding += DataGrid_RowEditEnding;

PS: Be sure that you use value types that are valid for the column (perhaps via a switch statement).

e.g.:switch on propertyName or propInfo... propInfo.SetValue(boundItem, (type) NEWVALUE, new object[] {});

                    switch (propertyName)                    {                        case "ColumnName":                            propInfo.SetValue(boundItem, ("ColumnName"'s type) NEWVALUE, new object[] { });                            break;                        default:                            break;                    }