Populate a datagridview with sql query results

前端 未结 9 1076
旧巷少年郎
旧巷少年郎 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条回答
  • 2020-12-02 23:50

    This is suppose to be the safest and error pron query :

        public void Load_Data()
            {
                using (SqlConnection connection = new SqlConnection(DatabaseServices.connectionString)) //use your connection string here
                {
                    var bindingSource = new BindingSource();
                    string fetachSlidesRecentSQL = "select top (50) * from dbo.slides order by created_date desc";
                    using (SqlDataAdapter dataAdapter = new SqlDataAdapter(fetachSlidesRecentSQL, connection))
                    {
                        try
                        {
                           SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
    
                            DataTable table = new DataTable();
                            dataAdapter.Fill(table);
                            bindingSource.DataSource = table;
                            recent_slides_grd_view.ReadOnly = true;
                            recent_slides_grd_view.DataSource = bindingSource;
                        }
                        catch (SqlException ex)
                        {
                           MessageBox.Show(ex.Message.ToString(), "ERROR Loading");
                        }
                        finally
                        {
                            connection.Close();
                        }
                    }
    
                }
            }
    
    0 讨论(0)
  • 2020-12-02 23:50

    if you are using mysql this code you can use.

    string con = "SERVER=localhost; user id=root; password=; database=databasename";
        private void loaddata()
    {
    MySqlConnection connect = new MySqlConnection(con);
    connect.Open();
    try
    {
    MySqlCommand cmd = connect.CreateCommand();
    cmd.CommandText = "SELECT * FROM DATA1";
    MySqlDataAdapter da = new MySqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    datagrid.DataSource = dt;
    }
    catch(Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    }
    
    0 讨论(0)
  • 2020-12-02 23:58

    You don't need bindingSource1

    Just set dataGridView1.DataSource = table;

    0 讨论(0)
提交回复
热议问题