从多个表更新数据网格视图

本文关键字:数据网 网格 视图 数据 更新 | 更新日期: 2024-10-25 23:36:59

我有datagridview,我必须用5个表填充。我声明了 SqlCommand 和 SqlConnection。之后,我像这样使用一些东西:

selCommand.Connection = conn;
dt = new DataTable();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = selCommand;
ad.Fill(dt);
dataGridView1.DataSource = dt;

因此,我在 datagridview 中有查询的列标题,但没有数据。我尝试使用此代码:

selCommand.Connection = conn;
dt = new DataTable();
SqlDataReader dr = selCommand.ExecuteReader();
dt.Load(dr);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
dr.Close();

正在工作,但我改变了一些东西,我不明白为什么它不起作用。

从多个表更新数据网格视图

试试这个:

DataTable table = null;
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
    try
    {
        connection.Open();
        SqlCommand cmd = connection.CreateCommand();
        cmd.CommandText = "SELECT * FROM Something WHERE Id = @Id";
        cmd.Parameters.Add(new SqlParameter("@Id", YourValue));
        using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
        {
            table = new DataTable();
            adapter.Fill(table);
        }
    }
    catch (Exception ex)
    {
        //Handle your exception;   
    }
}
dataGridView1.DataSource = table;