Programming for Everybody: November 2022

Fill dataGridview from Excel's sheet depend on comBobox in C# with source code

 




using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.Data.OleDb;

namespace excel_import

{

    public partial class Form6 : Form

    {

        public Form6()

        {

            InitializeComponent();

        }

        OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Ace.Oledb.12.0;" +

            @"Data Source=F:names2.Xlsx;Extended Properties = 'Excel 8.0;HDR=Yes'");

        private void Form6_Load(object sender, EventArgs e)

        {

            conn.Open();

            comboBox1.DataSource = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

            comboBox1.DisplayMember = "Table_Name";

            comboBox1.SelectedIndex = -1;

            comboBox1.SelectedText = "Select sheet";

            conn.Close();

        }


        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)

        {


        }


        private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)

        {

            OleDbCommand cmd = new OleDbCommand("Select * From [" + comboBox1.GetItemText(comboBox1.SelectedItem) + "]", conn);

            OleDbDataAdapter da = new OleDbDataAdapter(cmd);

            DataTable dt = new DataTable();

            da.Fill(dt);

            dataGridView1.DataSource = dt;

        }

    }

}