[英]How can I read all files from directory and put in an existing datagrindview
I have got this code. 我有这个代码。
private void button2_Click(object sender, EventArgs e)
{
dataGridView1.AllowUserToAddRows = false;
int xy = dataGridView1.Rows.Count;
string[] Files = System.IO.Directory.GetFiles(@"f:\ecet\");
foreach (string sFile in Files)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string fileCont = System.IO.File.ReadAllText(sFile);
dataGridView1.Rows[i].Cells[1].Value = fileCont.ToString();
}
}
}
I have got the fault. 我有错。 In the "ecet" folder i have got 3 files. 在“ ecet”文件夹中,我有3个文件。 (all .txt) (所有.txt)
when i run the programm, this is put only the content of the last txt file all three rows of datagrindview. 当我运行程序时,这仅将最后一个txt文件的内容放在datagrindview的所有三行中。
I want put first txt to the first row, the secound to the secound row and soo on. 我想将第一个txt放入第一行,将secound放入secound行,然后继续。
You could try this one: 您可以尝试以下方法:
// Declare an array, in which you will store the contents of your file.
string[] contents = new string[Files.Length];
// For each file in you Files collection read it's contents and add it to the contents array
for(int i=0; i<contents.Length; i++)
contents[i] = System.IO.File.ReadAllText(Files[i]);
// Set the datasource of your data grid view and databind it.
dataGridView1.DataSource = contents;
dataGridView1.dataBind();
private void button2_Click(object sender, EventArgs e)
{
dataGridView1.AllowUserToAddRows = false;
string[] Files = System.IO.Directory.GetFiles(@"f:\ecet\");
DataTable table = new DataTable();
table.Columns.Add("Content".ToString());
foreach (string sFile in Files)
{
string fileCont = System.IO.File.ReadAllText(sFile);
DataRow dr = table.NewRow();
dr["Content"] = fileCont;
table.Rows.Add(dr);
}
dataGridView1.DataSource = table;
}
Try this :) 尝试这个 :)
With your code you overwrite all Cells for every new file. 使用您的代码,您将覆盖每个新文件的所有单元。
here u can do it with Linq 在这里你可以用Linq做到
var files = System.IO.Directory.GetFiles(@"f:\ecet\").Select(t => Sytem.IO.File.ReadAllText(t)).ToList();
dataGridView1.DataSource = files;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.