How can I set the value of a datagrid cell using column and row values ​​of an index?

How can I insert a value into a specific datagrid cell using column columns and row indices. I have a row and column index saved as ints.

I got indexes as below. Im basically takes the cell value, column index and row index and sends in serialized XML to java, which sends it back, and it needs to put it in the same cell.

int column = dataGrid2.CurrentCell.Column.DisplayIndex; int row = dataGrid2.SelectedIndex; 

Thanks,

+4
source share
3 answers

For a datagrid, you access the rows through the Items property. Cells are a collection of an item.

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

This works as long as the data is bound to the datagrid during the current page life cycle. If it is not, I believe that you are stuck in control.

+1
source

There can be many ways to update WPF DataGridCell programmatically ...

One way is to update the value in the related data element itself. Thus, notifications of changes in properties will be triggered for all signed visual objects, including the DataGridCell ...

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 a DataGridComboBoxColumn you need to extract SelectedValuePath and use instead of propertyName .

Otherwise, add the cell to edit mode and update its contents using some behavior in EditingElementStyle ... I find this cumbersome.

Let me know if you really need it.

+1
source

I used a variant based on the WPF example to make the whole line 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: Make sure that you are using value types valid for the column (possibly using the switch statement).

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

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

All Articles