繁体   English   中英

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

[英]C# Adding 4923 Lines from a text file to DataGridView by skipping blank lines

我是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;
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM