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

T.Zacks 3,986 Reputation points
2021-11-10T17:43:36.15+00:00

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

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,230 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,036 Reputation points
    2021-11-10T17:53:11.943+00:00

    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.

    0 comments No comments

0 additional answers

Sort by: Most helpful