Reading from a DataGrid, not a csv file into an array / list

I have the following code snippet that reads a csv file with data and stores it in an array.

private static void ProcessFile() { var lines = File.ReadLines("Data.csv"); var numbers = ProcessRawNumbers(lines); ****Some variables I use later on**** var rowTotal = new List<double>(); var squareRowTotal = new List<double>(); } 

I would like to do the same by inserting data into a DataGridView using C # and not reading the csv file.

My csv file looks like this:

 2,5,6,8,4 5,8,3,5,7 7,7,9,3,5 7,8,4,5,6 

I would like to enter the above data into rows and columns in a DataGridView and handle the rows and numbers. I'm not sure how to do this, could you help me?

+4
source share
2 answers

You can handle a double loop:

 for (int rows = 0; rows < dataGrid.Rows.Count; rows++) { for (int cols= 0; cols < dataGrid.Rows[rows].Cells.Count; cols++) { var value = dataGrid.Rows[rows].Cells[cols].Value.ToString(); } } 
+1
source

As far as I understand your question, please explain in detail. I suggest the following:

Logic: Declare a string array and read each line and fill the data into an array of strings. Then convert it to datatable and bind it to a DataGridView. You can do rowTotal and SquareTotal events in a grid.

 private static void ProcessFile() { string lines; string[] ContentData; bool blnReadFile = true; while (blnReadFile) { lines = File.ReadLines("Data.csv"); if (String.IsNullOrEmpty(content)) { blnReadFile = false; } else { ContentData = ProcessRawNumbers(lines); /* Ihave retained your metod to get each line */ } } DataTable dt = ArrayToDataTable(ContentData); dg.DataSource = dt; /* dg refers to Datagrid */ dg.DataBind(); } public DataTable ArrayToDataTable(string[] arr) { DataTable dt = new DataTable(); string[] header = arr[0].Split(','); foreach (string head in header) { dt.Columns.Add(head); } for (int theRow = 0; theRow < arr.Length; theRow++) { if (theRow != 0) { string str = arr[theRow]; string[] item = str.Split(','); DataRow dr = dt.NewRow(); for (int theColumn = 0; theColumn < item.Length; theColumn++) { dr[theColumn] = item[theColumn]; } dt.Rows.Add(dr); } } return dt; } 
0
source

All Articles