将 table 的数据加载到 运行 时创建的 DataGridView

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

我试图在每次按下按钮时在运行时创建一个 DataGridView。
我还想在我的数据库中显示来自 table 的数据。

当我按下应该创建 DataGridView 并显示数据的按钮时,它什么也没做。它不会创建 DataGridView。

这是我的代码(table 称为“用品”):

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

您隐藏了大部分代码,但我怀疑您从未将 suppliesView(一个 datagridview?)添加到表单中。这是一个非常有效的示例代码:

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