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.
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.
Here are my codes:
ReadExcel Method
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
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;
}