首页 > 解决方案 > 如何在 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 程序。

标签: c#datagridviewdataset

解决方案


这是一个代码片段。所以我有一个带有一个 TabPage的TabControl 。 tabControl1

第 1 步:读取并获取文件总数并将文件路径存储在List<string>

第 2 步:根据文件计数生成TabPage.

第 3 步:读取 CSV 文件并将其存储在Datatable

第 4 步:对于TabPage添加并将DataGridView其映射DataSourceDataTable

请注意,这未经测试。

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;
    }

推荐阅读