1

I am looking for a code to copy a column of Datagrid to a double array.

  Period   Acc
  0.1      3
  1        4
  2        7
  5.5      10.5

For example, I would like to have a double array for Column Perioed. Datagrid name is dg. I tried to find out exisng Q&A but all I found were about window form or datagridview which include "Rows". I found Rows property is not in datagrid class but datagridview. Does anybody know how to do it? Thanks,

2 Answers 2

2

@Daloupe is correct. How are you populating the DataGrid in the first place? Working with the data source is much easier than trying to manage data directly from the DataGrid. For example, if your data is populated from a list of class objects called Data that has two double values (Period and Acc), you could use extension methods on the source list to extract the Period values.

// You have a list of Data elements List<Data> gridData that is the data 
// source of your DataGrid
double[] periods = gridData.Select(x => x.Period).ToArray();
Sign up to request clarification or add additional context in comments.

2 Comments

Sometime I need to edit numbers on datagrid window. then want to pass the edited numbers to array. Thanks,
If you are passing the value into an array that is separate from the data source for the DataGrid and want to keep it synchronized to the current collection, you would need to subscribe to the DataGrid.CellEditEnding event to update the array based on the new Period values if a change was made.
1

a verbose way to do it would be:

var colVals = List<double>();
foreach(var row in Datagrid.Rows)
{
     colVals.Add(Convert.ToDouble(row.Cells[0]));
}

perhaps?

Edit: Ahh you're using a Datagrid instead of a Datagridview, well that woudl depend on your data source, no?

3 Comments

Yes correct, data from the datatable are passed to datagrid in first place. The reason why I want to copy from datagrid is because I may need to edit some numbers on datagrid then pass to array for analysis.
If the DataGrid is bound to the datasource, then any changes made to the grid will change the source and vice versa. Whether you grab the data from the source, or from the grid, it's the same data.
In winForms you would add the datasource to a BindingSource, then use that as the datasource for the grid, but I'm not sure if you need to with WPF.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.