Populate a datagridview with sql query results

前端 未结 9 1112
旧巷少年郎
旧巷少年郎 2020-12-02 23:02

I\'m trying to present query results, but I keep getting a blank data grid. It\'s like the data itself is not visible

Here is my code:

 private void         


        
9条回答
  •  猫巷女王i
    2020-12-02 23:40

    You may try this sample, and always check your Connection String, you can use this example with or with out bindingsource you can load the data to datagridview.

    private void Employee_Report_Load(object sender, EventArgs e)
    {
            var table = new DataTable();
    
            var connection = "ConnectionString";
    
            using (var con = new SqlConnection { ConnectionString = connection })
            {
                using (var command = new SqlCommand { Connection = con })
                {
    
                    if (con.State == ConnectionState.Open)
                    {
                        con.Close();
                    }
    
                    con.Open();
    
                    try
                    {
                        command.CommandText = @"SELECT * FROM tblEmployee";
                        table.Load(command.ExecuteReader());
    
                        bindingSource1.DataSource = table;
    
                        dataGridView1.ReadOnly = true;
                        dataGridView1.DataSource = bindingSource1;
    
                    }
                    catch(SqlException ex)
                    {
                        MessageBox.Show(ex.Message + " sql query error.");
                    }
    
                }
    
            }
    
     }
    

提交回复
热议问题