I have written a C# code to read data from a csv
file. The data is in the form say:
2,3,4,5,6
4,2,4,5,6
4,5,6,3,2
5,3,5,6,3
The code to read it is:
var lines = File.ReadLines("Data.csv");
var numbers = ProcessRawNumbers(lines);
The function ProcessRawNumbers
is as follows:
private static List<List<double>> ProcessRawNumbers(IEnumerable<string> lines)
{
var numbers = new List<List<double>>();
/*System.Threading.Tasks.*/
Parallel.ForEach(lines, line =>
{
lock (numbers)
{
numbers.Add(ProcessLine(line));
}
});
return numbers;
}
private static List<double> ProcessLine(string line)
{
var list = new List<double>();
foreach (var s in line.Split(Separators, StringSplitOptions.RemoveEmptyEntries))
{
double i;
if (Double.TryParse(s, out i))
{
list.Add(i);
}
}
return list;
}
I would like to do the same with DataGridView
. How can this be achieved?
In DataGridView
I give input as follows:
Also, is it possible to have the number of columns change dynamically?
Data entered in a DataGridView
is stored in its rows and cells. To exctract the data, you have to manually iterate over the rows and cell:
public List<string[]> ExtractGridData(DataGridView grid)
{
int numCols = grid.Columns.Count;
List<string[]> list = new List<string[]>();
foreach (DataGridViewRow row in grid.Rows)
{
if (row.IsNewRow) // skip the new row
continue;
string[] cellsData = new string[numCols];
foreach (DataGridViewCell cell in row.Cells)
if (cell.Value != null)
cellsData[cell.ColumnIndex] = cell.Value.ToString();
list.Add(cellsData);
}
return list;
}
If you want to change the columns dynamically, you can access the Columns
property of the grid. For example, to add a column you can write:
dataGridView1.Columns.Add("NewColumn", "New Column");
Also note that using Parallel.ForEach
in your scenario has no advantage, because you have to process the data sequentially, and by using lock
statement, you forced the sequential processing. So there is no parallel proccessing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.