【问题标题】:Populate a datagridview with sql query results使用 sql 查询结果填充 datagridview
【发布时间】:2013-08-07 20:34:06
【问题描述】:

我正在尝试显示查询结果,但我不断得到一个空白的数据网格。 好像数据本身是不可见的

这是我的代码:

 private void Employee_Report_Load(object sender, EventArgs e)
 {
     string select = "SELECT * FROM tblEmployee";
     Connection c = new Connection();
     SqlDataAdapter dataAdapter = new SqlDataAdapter(select, c.con); //c.con is the connection string
     SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

     DataTable table = new DataTable();
     table.Locale = System.Globalization.CultureInfo.InvariantCulture;
     dataAdapter.Fill(table);
     bindingSource1.DataSource = table;

     dataGridView1.ReadOnly = true;        
     dataGridView1.DataSource = bindingSource1;
}

这段代码有什么问题?

【问题讨论】:

  • 在dataGridView中绑定数据

标签: c# winforms datagridview


【解决方案1】:

您的代码已修复。接下来忘记绑定源

 var select = "SELECT * FROM tblEmployee";
 var c = new SqlConnection(yourConnectionString); // Your Connection String here
 var dataAdapter = new SqlDataAdapter(select, c); 

 var commandBuilder = new SqlCommandBuilder(dataAdapter);
 var ds = new DataSet();
 dataAdapter.Fill(ds);
 dataGridView1.ReadOnly = true; 
 dataGridView1.DataSource = ds.Tables[0];

【讨论】:

  • 您可以“填写”DataTable 没问题。不需要DataSet
  • 它确实有效,但 DataSet 是额外的开销,没有用处。
  • @DonThomasBoyle 在第二个示例代码中,使用的类是SqlServerCe 而不是SqlServer。这可能会令人困惑。
  • 在我的情况下好像数据本身是不可见的
【解决方案2】:
String strConnection = Properties.Settings.Default.BooksConnectionString;
SqlConnection con = new SqlConnection(strConnection);

SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from titles";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);

DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;

【讨论】:

    【解决方案3】:

    你不需要bindingSource1

    只需设置dataGridView1.DataSource = table;

    【讨论】:

    • 您在 datagridview 中看到列了吗?如果是,那么您的查询没有返回任何行!
    • 我在 sql server 2008 中检查了我的查询,它确实返回了员工表的所有数据
    【解决方案4】:

    尝试将您的DataGridView 绑定到DataTableDefaultView

    dataGridView1.DataSource = table.DefaultView;
    

    【讨论】:

      【解决方案5】:

      这应该是最安全的错误代号查询:

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

      【讨论】:

        【解决方案6】:

        如果您将数据源设置为您添加到表单但未使用的数据集,您可能会得到一个空白的数据网格。如果您基于上述代码以编程方式设置数据源,请将其设置为 None。

        【讨论】:

          【解决方案7】:

          您可以尝试这个示例,并始终检查您的连接字符串,您可以使用此示例,无论是否使用 bindingsource,您都可以将数据加载到 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.");
                          }
          
                      }
          
                  }
          
           }
          

          【讨论】:

            【解决方案8】:

            您必须将属性表添加到 DataGridView 数据源

             dataGridView1.DataSource = table.Tables[0];
            

            【讨论】:

            • 已经有公认的答案,它提供的信息也比你做的多。这在这里是相当多余的。
            【解决方案9】:

            如果你用的是mysql这个代码你可以使用。

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

            【讨论】:

              【解决方案10】:

              晚了几年,但这是其他人最简单的方法。

              String connectionString = @"Data Source=LOCALHOST;Initial Catalog=DB;Integrated Security=true";
              
              SqlConnection cnn = new SqlConnection(connectionString);
              SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblEmployee;", cnn);
              
              DataTable data = new DataTable();
              sda.Fill(data);
              
              DataGridView1.DataSource = data;
              

              没有必要使用DataSetDataTable 应该足够好了。 SQLCommandBuilder 也不需要。

              【讨论】:

                【解决方案11】:

                我认为这是从一开始就编写的专业方式,但是您可以将此代码与 MySQL 一起使用,但我认为它们是相同的:

                1/

                using System.Data; AND using MySql.Data.MySqlClient;
                

                2/

                MySqlConnection con = new MySqlConnection("datasource=172.16.2.104;port=3306;server=localhost;database=DB_Name=root;password=DB_Password;sslmode=none;charset=utf8;");
                        MySqlCommand cmd = new MySqlCommand();
                

                3/

                public void SetCommand(string SQL)
                {
                    cmd.Connection = con;
                    cmd.CommandText = SQL;
                
                }
                private void FillGrid()
                {
                    SetCommand("SELECT * FROM `transport_db`ORDER BY `id` DESC LIMIT 15");
                    DataTable tbl = new DataTable();
                    tbl.Load(cmd.ExecuteReader());
                    dataGridView1.DataSource = tbl;
                }
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2021-01-04
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-05-27
                  • 2014-05-11
                  • 1970-01-01
                  • 1970-01-01
                  • 2019-04-06
                  相关资源
                  最近更新 更多