Pra*_*tik 1 .net c# csv datagridview winforms
我在Windows Forms .NET 3.5中有以下内容
它适用于记录小于10,000的csv,但对于30,000以上的记录则较慢.输入csv文件可以在1到1,00,000条记录之间进行任何记录
目前使用的代码:
/// <summary>
/// This will import file to the collection object
/// </summary>
private bool ImportFile()
{
try
{
String fName;
String textLine = string.Empty;
String[] splitLine;
// clear the grid view
accountsDataGridView.Rows.Clear();
fName = openFileDialog1.FileName;
if (System.IO.File.Exists(fName))
{
System.IO.StreamReader objReader = new System.IO.StreamReader(fName);
do
{
textLine = objReader.ReadLine();
if (textLine != "")
{
splitLine = textLine.Split(',');
if (splitLine[0] != "" || splitLine[1] != "")
{
accountsDataGridView.Rows.Add(splitLine);
}
}
} while (objReader.Peek() != -1);
}
return true;
}
catch (Exception ex)
{
if (ex.Message.Contains("The process cannot access the file"))
{
MessageBox.Show("The file you are importing is open.", "Import Account", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
MessageBox.Show(ex.Message);
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
样本输入文件:
18906,Y
18908,Y
18909,Y
18910,Y
18912,N
18913,N
需要一些关于优化此代码的建议,以便在网格中快速读取和查看.
List<string[]> rows = File.ReadAllLines("Path").Select(x => x.Split(',')).ToList();
DataTable dt = new DataTable();
dt.Columns.Add("1");
dt.Columns.Add("2");
rows.ForEach(x => {
dt.Rows.Add(x);
});
dgv.DataSource = dt;
Run Code Online (Sandbox Code Playgroud)
试试看,我怀疑你在数据网格中有某种形式的列名,现在我只做了1和2.
要根据原始代码进行过滤,请使用:
List<string[]> rows = File.ReadAllines("Path").Select(x => x.Split(',')).Where(x => x[0] != "" && x[1] != "").ToList();
Run Code Online (Sandbox Code Playgroud)
从列表中获取列 DataGridView
dt.Columns.AddRange(dgv.Columns.Cast<DataGridViewColumn>().Select(x => new DataColumn(x.Name)).ToArray());
Run Code Online (Sandbox Code Playgroud)