如何读取文本文件,然后使用分隔线放置数据?

时间:2014-01-22 23:06:44

标签: c# file-io streamreader

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()

3 个答案:

答案 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);
}

如果您需要在dataGridView1dataGridView2之间来回切换,请尝试以下操作:

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}}并循环遍历数组。