简体   繁体   English

如何访问TabPage内动态添加的DataGridView并获取值?

[英]How to access dynamically added DataGridView inside a TabPage and get values?

I have made a program that can import an excel file and insert all the sheets in a dynamically added tabpage with a dynamically added datagridview. 我制作了一个程序,可以导入一个excel文件,并将所有工作表插入具有动态添加的datagridview的动态添加的选项卡中。

I want to insert the values of the KPI column depending on the tab selected on my combobox and everytime you change the tabpage, the combobox changes too. 我想根据在组合框中选择的选项卡插入KPI列的值,并且每次更改选项卡页面时,组合框也会更改。 图片

Here are my codes: 这是我的代码:

ReadExcel Method ReadExcel方法

  public static void ReadExcel(ComboBox cboSheet, TabControl tabCon)
    {
       try
       {
           OpenFileDialog openFileDialog = new OpenFileDialog();
           openFileDialog.Filter = "Excel Files| *.xls; *xlsx";
           openFileDialog.ShowDialog();

           if (!string.IsNullOrEmpty(openFileDialog.FileName))
           {
               OleDbcon = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + openFileDialog.FileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'");
               OleDbcon.Open();

               DataTable dt = OleDbcon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
               OleDbcon.Close();

               cboSheet.Items.Clear();

               int width = 1330;
               int height = 565;
               //1338, 590

               for (int i = 0; i < dt.Rows.Count; i++)
               {
                    if (!dt.Rows[i]["Table_Name"].ToString().Contains("FilterDatabase") && !dt.Rows[i]["Table_Name"].ToString().EndsWith("$'"))
                    {
                       String sheetName = dt.Rows[i]["Table_Name"].ToString();
                       sheetName = sheetName.Substring(0, sheetName.Length - 1);
                        //cboSheet.Items.Add(sheetName);

                        TabPage tp = new TabPage(sheetName);

                        DataGridView dataGridView = new DataGridView();
                        tp.Controls.Add(dataGridView);
                        tabCon.Controls.Add(tp);
                        CreateDataGrid(dataGridView, sheetName);
                        dataGridView.Size = new Size(width, height);
                        System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle = new System.Windows.Forms.DataGridViewCellStyle();

                        //KPI Column
                    }
               }
           }
       }

       catch (Exception e)
       {
           MessageBox.Show(e.ToString());

       }

    }

CreateDataGrid Method CreateDataGrid方法

  public static void CreateDataGrid(DataGridView dataGridView1, string TabName)
    {
        OleDbDataAdapter oleAdapt = new OleDbDataAdapter("Select * from [" + TabName + "$]", ExcelMethods.OleDbcon);


        DataTable dt = new DataTable();

        oleAdapt.Fill(dt);

        dataGridView1.DataSource = dt;
    }

Below is a simple win form program that demonstrates what I described in my comments. 下面是一个简单的获胜表格程序,该程序演示了我在评论中描述的内容。 The form contains an empty ComboBox named cb_KPI . 该表单包含一个名为cb_KPI的空ComboBox In addition it contains an empty TabControl named tabControl1 . 另外,它包含一个名为tabControl1的空TabControl

A global variable is created AllDataTables . 创建一个全局变量AllDataTables AlldataTables is a DataSet such that each DataTable in the DataSet is an existing worksheet from the user selected Excel workbook. AlldataTables是一个DataSet ,使得每个DataTable中的DataSet是选自Excel工作簿用户的现有工作表。 This is used to hold the DataTable for each TabPage … ie AllDataTables.Tables[0] is the DataTable for tabControl1.TabPages[0] . 这用于保持所述DataTable针对每个TabPage ...即AllDataTables.Tables[0]DataTabletabControl1.TabPages[0]

When the form is loaded, AllDataTables is filled with the user selected workbook's worksheets… then, a loop through all the tables adds a new TabPage to the tabControl1 for each table. 加载表单后,用用户选择的工作簿的工作表填充AllDataTables …然后,遍历所有表的循环会将新的TabPage到每个表的tabControl1中。 Finally, the cb_KPI combo box is updated to contain the values for the currently selected TabPage . 最后, cb_KPI组合框将更新为包含当前所选TabPage的值。

DataSet AllDataTables;

public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  AllDataTables = GetDSFromExcel();
  foreach (DataTable dt in AllDataTables.Tables) {
    tabControl1.TabPages.Add(GetTabPageWithGrid(dt));
  }
  cb_KPI.DataSource = SetKPI_ValuesForComboBox(AllDataTables.Tables[tabControl1.SelectedIndex]);
}

The GetDSFromExcel method returns a DataSet from a user selected Excel file where each DataTable in the DataSet is a worksheet from the user selected Excel file. GetDSFromExcel方法返回一个DataSet选自Excel文件一个用户,其中每个DataTable中的DataSet是选自Excel文件中的用户工作表。

private DataSet GetDSFromExcel() {
  DataSet ds = new DataSet();
  try {
    OpenFileDialog openFileDialog = new OpenFileDialog {
      Filter = "Excel Files| *.xls; *xlsx"
    };
    openFileDialog.ShowDialog();
    if (!string.IsNullOrEmpty(openFileDialog.FileName)) {
      using (OleDbConnection OleDbcon = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + openFileDialog.FileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'")) {
        OleDbcon.Open();
        DataTable WorkbookSheetInfo = OleDbcon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        String sheetName;
        DataTable dt;
        OleDbDataAdapter oleAdapt;
        for (int i = 0; i < WorkbookSheetInfo.Rows.Count; i++) {
          if ((WorkbookSheetInfo.Rows[i]["Table_Name"].ToString().EndsWith("$'")) ||
              (WorkbookSheetInfo.Rows[i]["Table_Name"].ToString().EndsWith("$"))) {
            sheetName = WorkbookSheetInfo.Rows[i]["Table_Name"].ToString();
            dt = new DataTable(sheetName.Replace("'", "").Replace("$", ""));
            oleAdapt = new OleDbDataAdapter("Select * from [" + sheetName + "]", OleDbcon);
            oleAdapt.Fill(dt);
            ds.Tables.Add(dt);
          }
        }
      }
    }
  }
  catch (Exception e) {
    MessageBox.Show("ReadExcelIntoDS_Error" + e.ToString());
  }
  return ds;
}

The GetTabPageWithGrid method is given a DataTable and returns a single TabPage with a DataGridView such that the DataGridView 's DataSource will be the given DataTable GetTabPageWithGrid方法被赋予一个DataTable并返回一个带有DataGridView TabPage ,这样DataGridViewDataSource将成为给定的DataTable

private TabPage GetTabPageWithGrid(DataTable dt) {
  TabPage tp = new TabPage(dt.TableName.Replace("'", "").Replace("$", ""));
  tp.Controls.Add(GetDGV(dt));
  return tp;
}

private DataGridView GetDGV(DataTable dt) {
  return new DataGridView {
    Size = new Size(1000, 400),
    Name = "datagridView" + dt.TableName,
    DataSource = dt,
    ScrollBars = ScrollBars.Both
  };
}

Next is the needed code to keep the cb_KPI combo box consistent when the user selects a different tab page. 接下来是所需的代码,当用户选择其他选项卡页面时,该代码可使cb_KPI组合框保持一致。 Wiring up the TabControls SelectedIndexChanged event might be helpful here, the code simply loops through the DataTable and gathers all the different “KPI” string values and stores them into a List<string> then returns the completed list. 在这里连接TabControls SelectedIndexChanged事件可能会有所帮助,该代码仅循环遍历DataTable并收集所有不同的“ KPI”字符串值,并将它们存储在List<string>然后返回完成的列表。 This new list is then used as a DataSource for the cb_KPI combo box. 然后,此新列表将用作cb_KPI组合框的DataSource Obviously, if the DataTable is large or there are many different tables, you may consider saving these lists of strings instead of regenerating the list every time the user selects a different tab. 显然,如果DataTable很大或有许多不同的表,则可以考虑保存这些字符串列表,而不是每次用户选择其他选项卡时都重新生成列表。 NOTE: The code below assumes there is a column in the table named “KPI”. 注意:以下代码假定表中有一个名为“ KPI”的列。

private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) {
  cb_KPI.DataSource = SetKPI_ValuesForComboBox(AllDataTables.Tables[tabControl1.SelectedIndex]);
}

private List<string> SetKPI_ValuesForComboBox(DataTable dt) {
  List<string> kpiList = new List<string> {
    "All"
  };
  foreach (DataRow row in dt.Rows) {
    if (!kpiList.Contains(row["KPI"].ToString()))
      kpiList.Add(row["KPI"].ToString());
  }
  return kpiList;
}

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM