c# 读取空行_C#通过跳过空行将4923行从文本文件添加到DataGridView
I am new to C#. I have a huge text file consisting of 4923 lines of data that I wish to add to a DataGridView. The text file has a lot of spaces and blank lines in between sentences. I want that all the blank lines and spaces be skipped and load the contents to the DataGridView. Can someone give me a solution to achieve this? Can this be achieved without using DataTables and Datasource?
If my question is not clear please let me know. There may be mistakes in my code. Please help me rectify it
Thanks
This is my code
public void textload()
{
List str = new List();
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;
}
Talk1:
Try .Replace(' ','').ToString()
Talk2:
Where to add the above line sir?
Talk3:
Can you please show us your sample text you want to parse ? IndexOutOfBoundException is different from OutOfMemoryException The number of columns in grid and in your text files are mismatch.
Solutions1
One option is to filter out empty strings as soon as you've read it. This can be done with LINQ Where and passing condition that checks string for not being whitespace only. String.IsNullOrWhitepspace covers that (in addition it would check for null that will not happen in case of using ReadAllLines).
string[] lines = File.ReadAllLines(st)
.Where(s => !String.IsNullOrWhitespace(s))
.ToArray();
Talk1:
Thanks @ALexie ,now that I have filtered all empty strings ,how to load the contents to the DataGridView?
Talk2:
, Just a side note:. If the file is very large in size you might get OutOfMemoryException if you loads complete contents at once.
Talk3:
you're right.I am getting IndexOutOfBound Exception at dataGridView1.Rows[i].Cells[i].Value=lines[i];.Can you Please tell me how to load data to DataGridview
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)