Search code examples
c#winformsdatagridviewoledb

Load the data of a table into a DataGridView created at run-time


I'm trying to create a DataGridView at runtime whenever I press a button.
I also want to present the data from a table in my database.

When I press the Button that should create a DataGridView and show the data, but it just does nothing. It doesn't create the DataGridView.

Here is my code (the table is called "supplies"):

public partial class managerpage : Form
{
    int idWorkersDB = 0;
    int idAccountsDB = 1;
    int idSuppliersDB = 2;
    int idOtherDB = 3;
    public static DataGridView workersView = new DataGridView();
    public static DataGridView suppliesView = new DataGridView();
    public static DataGridView accountsView = new DataGridView();
    int clickedID;

    private void picBoxSuppliers_MouseUp(object sender, MouseEventArgs e)
    {
        suppliesView.Location = new Point(59, 51);
        suppliesView.Size = new Size(749, 399);
        
        clickedID = idSuppliersDB;
        dataDBPanel.Visible = true;
        dataDBPanel.Dock = DockStyle.Fill;
        
        titleDataLbl.Text = "Suppliers Data";
        titleDataLbl.Left = (this.Width - titleDataLbl.Width) / 2;
        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=G:\project\FUCKINGVISUALSTUDIOISSOSHIT\loginData.mdb");
        OleDbDataAdapter cmd = new OleDbDataAdapter("SELECT * FROM supplies", con);
        con.Open();
        DataTable tbl = new DataTable();
        cmd.Fill(tbl);
        con.Close();

        suppliesView.DataSource = tbl;
        suppliesView.Show();
    }
}

Solution

  • You are hiding most of the code, but I suspect you never add that suppliesView (a datagridview?) to the form. Here is a sample code that works wonderfully well:

    void Main()
    {
        DataTable t = new DataTable();
        using (var con = new SqlConnection(@"server=.;Database=Northwind;Trusted_Connection=yes"))
        using (var cmd = new SqlCommand(@"select * from Customers", con))
        {
            con.Open();
            t.Load(cmd.ExecuteReader());
            con.Close();
        }
    
        
        var f = new Form();
        var dgv = new DataGridView { Dock = DockStyle.Fill, DataSource=t};
        f.Controls.Add(dgv);
        f.Show();
    }