How can i insert a value into a specific datagrid cell by using the cells column and row indexs. I have the Row and Column index saved as ints.
I got the indexs as below. Im basically taking the cell value, the column index and the row index and sending as a serialized XML to java which is sending it back and needs to put it in the same cell.
int column = dataGrid2.CurrentCell.Column.DisplayIndex;
int row = dataGrid2.SelectedIndex;
Thanks,
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.
If you use DataGrid you can try it
DataRowView rowView = (dtGrid.Items[rows] as DataRowView); //Get RowView
rowView.BeginEdit();
rowView[col] = "Change cell here";
rowView.EndEdit();
dtGrid.Items.Refresh(); // Refresh table
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With