c# - 如何在 C# 循环中的选项卡中创建 Datagridview
问题描述
我正在开发项目,我必须读取多个 CSV 文件并在 DataGrid 中查看。现在这里的挑战是如果有 5 个文件,我必须创建 5 个不同的选项卡才能在 Datagrid 中查看,这是我无法做到的。这是我的代码:
DataSet ds = new DataSet();
foreach (String file in openFileDialogCSVFilePath.FileNames)
{
string fileLocation = file;
string fileName = Path.GetFileName(@fileLocation);
CsvReader reader = new CsvReader(fileLocation);
ds = reader.RowEnumerator;
}
dGridCSVdata.DataSource = ds;
dGridCSVdata.DataMember = "The Data";
谁能帮助我如何做到这一点?提前致谢。
更新:
我想以语法方式创建 Tab 程序。
解决方案
这是一个代码片段。所以我有一个带有一个 TabPage的TabControl 。 tabControl1
第 1 步:读取并获取文件总数并将文件路径存储在List<string>
第 2 步:根据文件计数生成TabPage
.
第 3 步:读取 CSV 文件并将其存储在Datatable
第 4 步:对于TabPage
添加并将DataGridView
其映射DataSource
到DataTable
请注意,这未经测试。
private void frmMain_Load(object sender, EventArgs e)
{
//Get Total Number of File to create Total Tab
//Pass the count in the for loop
//Store the File Path of Each File in List<string> lstFilePath
for (int i = 0; i < 5; i++) //i< lstFilePath.Count
{
//Create Tab Programatically
this.tabControl1.TabPages.Add("Tab Page"+ (i+1).ToString());
//Create DataTable to read and Store the CSV File Data
DataTable Dt = new DataTable();
//Based on the i value get the File Path from lstFilePath
//and pass it to Function below
Dt = ConvertCSVtoDataTable("");
DataGridView grid = new DataGridView();
this.tabControl1.TabPages[i].Controls.Add(grid);
grid.DataSource = Dt;
}
}
public static DataTable ConvertCSVtoDataTable(string strFilePath)
{
DataTable dt = new DataTable();
using (StreamReader sr = new StreamReader(strFilePath))
{
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = sr.ReadLine().Split(',');
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
dt.Rows.Add(dr);
}
}
return dt;
}
推荐阅读
- python-2.7 - 如何为 OpenNMT-py (pytorch) 提供多 GPU 支持?
- sorting - 如何在 Elasticsearch 2.4.4 上进行自然排序
- python-3.x - 如何将双端队列数组中每个双端队列的所有值附加到一个数组中?(这也删除了每个双端队列中的第一个重复节点)
- java - 通过连接防止 Oracle 数据库错误
- google-apps-script - Google表格工具提示整数差异按列
- php - 使用超级 gloable 变量 $_GLOBALS 时未定义的变量
- android - Android 应用链接失败,SingleHostAsyncVerifier 返回失败
- javascript - 如何使用 tensorflow.js 正确上传 angular 的预训练模型?
- php - 如何循环使用条件
- nuxt.js - nuxt 生成的 dist 文件返回 net::ERR_FILE_NOT_FOUND