我是窗口应用程序的新手。
我编写了一个代码来读取文件夹内的文件并逐行读取并找到一些字符串并将其计数显示给dataGridView。
我想填充一个不起作用的 dataGridview。
我在互联网上尝试了不同的方法,但都没有奏效。
我知道我可能会犯一个愚蠢的错误。
我的代码如下
public class FileDetail
{
public string filename;
public int openConnectionCount;
public int closeConnectionCount;
}
private void button1_Click(object sender, EventArgs e)
{
int openConnectionCount = 0;
int closeConnectionCount = 0;
List<FileDetail> fileDetails =new List<FileDetail>();
foreach (string file in Directory.EnumerateFiles(textBox1.Text, "*.*", SearchOption.AllDirectories))
{
FileDetail fileDetail =new FileDetail();
fileDetail.filename = file;
// Read the file as one string.
using (StreamReader myFile = new StreamReader(file))
{
string line;
while ((line = myFile.ReadLine()) != null)
{
if (line.Contains(" OpenConnection()")) openConnectionCount++;
if (line.Contains(" CloseConnection()")) closeConnectionCount++;
}
fileDetail.openConnectionCount = openConnectionCount;
fileDetail.closeConnectionCount = closeConnectionCount;
}
fileDetails.Add(fileDetail);
openConnectionCount = 0;
closeConnectionCount = 0;
}
dataGridView1.AutoGenerateColumns = false;
dataGridView1.Columns.Add("filename", "File Name");
dataGridView1.Columns.Add("openConnectionCount", "Open Connection");
dataGridView1.Columns.Add("closeConnectionCount", "close Connection");
dataGridView1.Columns[0].DataPropertyName = "filename";
dataGridView1.Columns[1].DataPropertyName = "openConnectionCount";
dataGridView1.Columns[2].DataPropertyName = "closeConnectionCount";
var filenamesList = new BindingList<FileDetail>(fileDetails); // <-- BindingList
dataGridView1.DataSource = filenamesList;
//dataGridView1.DataSource = fileDetails;
//dataGridView1.b
//foreach (var fileDetail in fileDetails)
//{
// label1.Text += "FileName:=" + fileDetail.filename + "\t Open Connection:= " +
// fileDetail.openConnectionCount + "\t close connection:=" +
// fileDetail.closeConnectionCount+"\n";
//}
}
编辑:-
我已经关注了一些相同的链接
如何将列表绑定到dataGridView?
http://social.msdn.microsoft.com/Forums/eu/csharplanguage/thread/766c7b46-6431-4ec1-8e74-50f718c6606b