在winforms中向datagridview中添加更多csv文件



这是我为了导入csv而按下的按钮:

private void btnOpen_Click_1(object sender, EventArgs e)
{

using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
//  string[] files = Directory.GetFiles(fbd.SelectedPath);
string[] csvFiles = Directory.GetFiles(@"D:CSV", "*.csv");
foreach (string filePath1 in csvFiles)
{
BindData(filePath1);

}
}
}
}

这是为每个csv调用的方法。问题是,每次导入最后一个csv文件时,它都会生成datagridview。我想要一种方法来添加所有的记录,而不仅仅是我最后导入的csv:

private void BindData(string filePath)
{

DataTable dt = new DataTable();

using (TextFieldParser parser = new TextFieldParser(filePath))
{
// configure your parser to your needs
parser.TextFieldType = FieldType.Delimited;
parser.Delimiters = new string[] { ";" };
parser.HasFieldsEnclosedInQuotes = false; // no messy code if your data comes with quotes: ...;"text value";"another";...
// read the first line with your headers
string[] fields = parser.ReadFields();
// add the desired headers with the desired data type
dt.Columns.Add(fields[0], typeof(string));
dt.Columns.Add(fields[1], typeof(string));
dt.Columns.Add(fields[6], typeof(float));
dt.Columns.Add(fields[7], typeof(float));
dt.Columns.Add(fields[8], typeof(string));
dt.Columns.Add(fields[9], typeof(string));

// read the rest of the lines from your file
while (!parser.EndOfData)
{
// all fields from one line
string[] line = parser.ReadFields();
// create a new row 
DataRow row = dt.NewRow();
// put data values; cast if needed - this example uses string type columns
row[0] = line[0];
row[1] = line[1];
row[2] = line[6];
row[3] = line[7];
row[4] = line[8];
row[5] = line[9];
// add the newly created and filled row
dt.Rows.Add(row);

}
}
this.dataGridView1.DataSource = dt;
// asign to DGV

}

改变这一行

DataTable dt = new DataTable();

所以它说:

DataTable dt = (this.dataGridView1.DataSource as DataTable) ?? new DataTable();

因此,您可以重用现有的数据源或创建一个新的,如果它没有设置

最新更新