[英]Reading data from dataGridView instead of a csv file in C#
I have written a C# code to read data from a csv
file. 我已经编写了C#代码以从csv
文件读取数据。 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: 函数ProcessRawNumbers
如下:
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
. 我想对DataGridView
做同样的事情。 How can this be achieved? 如何做到这一点?
In DataGridView
I give input as follows: 在DataGridView
我输入如下:
Also, is it possible to have the number of columns change dynamically? 另外,是否可以使列数动态变化?
Data entered in a DataGridView
is stored in its rows and cells. 在DataGridView
输入的数据存储在其行和单元格中。 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. 如果要动态更改列,则可以访问网格的Columns
属性。 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. 还要注意,在您的方案中使用Parallel.ForEach
没有优势,因为您必须顺序处理数据,并且通过使用lock
语句强制执行顺序处理。 So there is no parallel proccessing. 因此,没有并行处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.