question

TZacks-2728 avatar image
0 Votes"
TZacks-2728 asked karenpayneoregon answered

C# How to refactor my code to accumulate data faster from datagridview

I am showing data through datagridview. on a button click i have to extract data from datagridview and populate a list.

please see the screen shot how my data is looking.
148229-ww.png

i have two for loop to extract data. .here period data is coming horizontally.

see this code. by this code i am storing data into List<T>

 private void button1_Click_1(object sender, EventArgs e)
 {
  string section = "", lineitem = "", xfundcode = "", period = "";
  double periodvalue = 0;
  List<Data> _data = new List<Data>();
    
  for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
  {
  section = dataGridView1.Rows[r].Cells[0].Value.ToString();
  lineitem = dataGridView1.Rows[r].Cells[1].Value.ToString();
  xfundcode = dataGridView1.Rows[r].Cells[2].Value.ToString();
    
  for (int c = 3; c <= dataGridView1.Columns.Count - 1; r++)
  {
  period = dataGridView1.Columns[c].HeaderText;
  periodvalue = Convert.ToDouble(dataGridView1.Rows[r].Cells[c].Value.ToString());
    
  _data.Add(new Data
  {
  Section = section,
  LineItem = lineitem,
  XFundCode = xfundcode,
  Period = period,
  PeriodValue = periodvalue
  });
  }
  }
 }

i have huge number of rows & column. the approach i am following to accumulate data is taking long time for huge data. please guide how to refactor my code sample to speed up the data accumulation.

here can i use LINQ to accumulate data from datagridview because LINQ is faster.

can i use Parallel For to accumulate data from datagridview because it is faster.

please discuss with some approach which will be faster and accurate too.

Thanks





dotnet-csharp
ww.png (252.6 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered

High level, its always better to not access cell data, instead populate your DataGridView with a DataTable or a List<T> coupled with a SortableBindingList and BindingSource which when done this way you can iterate data via for or foreach or even better using LINQ/Lambda to get to information your after.

Bottom line, avoid accessing cells, always go to the data source which is strongly typed.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.