private void open(object sender, EventArgs e)
{
OpenFileDialog openDialog = new OpenFileDialog();
if (openDialog.ShowDialog() == DialogResult.OK)
{
string[] lines = File.ReadAllLines(openDialog.FileName);
foreach (string line in lines)
{
var text = line.Split(',', '\n');
dataGridView1.Rows.Add(text);
}
}
}
所以在这段代码中,我可以读取一个文本文件,但我只能像在1格一样。以下是示例文本文件的样子:
test,1,2,3,4,5,6,
testing,7,8,9,10,11,12,
working,13,14,15,16,17,18,
multiline,19,20,21,22,23,24,
NEXTDATA
see,25,26,36,46,56,66,
program,7,8,9,10,11,12,
macroer,13,14,15,16,17,18,
readextra,19,20,21,22,23,24,
因此,如果我到达名为“NEXTDATA”的行,我希望将这些数据放入dataGridView2
。如何检查它是否到达该行,然后它将与dataGridView1
中的代码执行相同的操作?
我也使用ReadLine()
或ReadAllLines()
?
答案 0 :(得分:6)
尝试使用以下内容:
var targetGridView = dataGridView1;
foreach (string line in lines)
{
if (line == "NEXTDATA")
{
targetGridView = dataGridView2;
continue;
}
var text = line.Split(',', '\n');
targetGridView.Rows.Add(text);
}
如果您需要在dataGridView1
和dataGridView2
之间来回切换,请尝试以下操作:
var targetGridView = dataGridView1;
foreach (string line in lines)
{
if (line == "NEXTDATA")
{
targetGridView = (targetGridView == dataGridView1)
? dataGridView2 : dataGridView1;
continue;
}
var text = line.Split(',', '\n');
targetGridView.Rows.Add(text);
}
答案 1 :(得分:5)
存储对您要添加的GridView
的引用..然后根据需要翻转它:
var currentGridView = dataGridView1;
foreach (string line in lines)
{
if (line == "NEXTDATA") {
currentGridView = dataGridView2;
continue;
}
var text = line.Split(',', '\n');
currentGridView.Rows.Add(text);
}
答案 2 :(得分:3)
这样的东西?
string[] lines = File.ReadAllLines(openDialog.FileName);
DataGridView dgv = dataGridView1;
foreach (string line in lines)
{
if(line == "NEXTDATA")
{
dgv = dataGridView2;
continue;
}
var text = line.Split(',', '\n');
dgv.Rows.Add(text);
}
我也使用
ReadLine()
或ReadAllLines()
?
由您决定 - ReadLine
读取一行,ReadAllLines
将整个文件读入一个字符串数组,因此您可以循环,每次调用ReadLine
,或者调用{{ 1}}并循环遍历数组。