Home > Mobile >  Load a table into a run-time created DataGridView from database - C# forms
Load a table into a run-time created DataGridView from database - C# forms

Time:03-20

I'm trying to create a datagridview at runtime whenever I press a button, I also want to insert a table there from my database. When I press the button that should create the datagridview with the table from my database it just does nothing... It doesn't create the datagridview.

Here is my code:

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

Yes the table is called "supplies"

Any help will be very appreciated :)

CodePudding user response:

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();
}
  • Related