C#通过跳过空行将文本文件中的4923行添加到DataGridView中

本文关键字:4923行 DataGridView 文件 添加 文本 | 更新日期: 2023-09-27 18:24:01

我是C#的新手。我有一个由4923行数据组成的巨大文本文件,我希望将其添加到DataGridView中。文本文件在句子之间有很多空格和空行。我希望跳过所有的空行和空格,并将内容加载到DataGridView中。有人能给我一个实现这一目标的解决方案吗?这可以在不使用DataTables和Datasource的情况下实现吗?

如果我的问题不清楚,请告诉我。我的代码可能有错误。请帮我纠正

感谢

这是我的代码

public void textload()
{
        List<string> str = new List<string>();
        String st = "";
        //Path to write contents to text file
        string filename = @"E:'Vivek'contentcopy'clientlist.txt";
        Form.CheckForIllegalCrossThreadCalls = false;
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.FileName = "";
        ofd.Filter = "csv files|*.csv|txt files|*.txt|All Files|*.*";
        ofd.ShowDialog();
        st = ofd.FileName;
        if (string.IsNullOrEmpty(ofd.FileName))
            return;
        string[] lines = File.ReadAllLines(st);
        for (int i = 0; i < lines.Length; i++)
        {
            listBox1.Items.Add(lines[i]);
            string[] s = lines[i].Split(' ');
            MessageBox.Show(s.Length.ToString());
            str.Add(lines[i]);
            dataGridView1.Rows.Add();
            if (s[i] == null && s[i] == " ") 
            {
                    continue; 
            }        
            dataGridView1.Rows[i].Cells[i].Value=s[i];
            //dataGridView1.Rows[i].Cells[10].Value = s[10];
            //dataGridView1.Rows[i].Cells[11].Value = s[11];
            //dataGridView1.Rows[i].Cells[12].Value = s[12];
            //dataGridView1.Rows[i].Cells[13].Value = s[13];
            //dataGridView1.Rows[i].Cells[14].Value = s[14];
            //dataGridView1.Rows[i].Cells[15].Value = s[15];
       }
       File.WriteAllLines(filename, str);
       dataGridView1.ReadOnly = true;
}

C#通过跳过空行将文本文件中的4923行添加到DataGridView中

一个选项是在阅读后立即过滤掉空字符串。这可以通过LINQ Where和检查字符串是否仅为空白的传递条件来完成。String.IsNullOrWhitepspace涵盖了这一点(此外,它将检查在使用ReadAllLines的情况下不会发生的null)。

 string[] lines = File.ReadAllLines(st)
     .Where(s => !String.IsNullOrWhitespace(s))
     .ToArray();