【问题标题】:How to add a column when using SqlDataAdapter to fill a datagridview使用SqlDataAdapter填充datagridview时如何添加列
【发布时间】:2016-12-14 16:03:47
【问题描述】:

我正在使用 SQL 来填充我的数据网格视图。我是这样做的:

string cn = ConfigurationManager.ConnectionStrings["Scratchpad"].ConnectionString;
SqlConnection myConnection = new SqlConnection(cn);

string sql = "some text here";
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, myConnection);
DataSet ds = new DataSet();
myConnection.Open();
dataadapter.Fill(ds, "Authors_table");
myConnection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";

现在它会删除旧的 datagridview 并粘贴选择。但我只想将数据添加到现有数据的右侧。

提前致谢

【问题讨论】:

  • 您的问题是关于如何使DataGridView 反映您在DataSet 中的数据,或者如何使DataSet 具有您想要的数据?
  • 听起来好像你想在一个DataSet中填充一个DataTable,然后在DataTable的一个附加列中添加额外的数据,匹配记录ID,这样每一行都会得到新列中的适当数据值。对吗?
  • @AnnL。这确实是正确的先生
  • 你能解决你的问题吗?

标签: c# sql datagridview sqldataadapter


【解决方案1】:

您在SqlDataAdapter 中使用的查询中的SQL Inner Join 听起来可以满足此要求。如果您能够通过匹配键将两个数据源连接在一起,则只需将数据拉下一次。但我会假设这对你不起作用是有原因的。

您实际上可以使用DataSet 做您想做的事,但您需要采取更多步骤:

string sql = "The first query"
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, myConnection);
DataSet ds = new DataSet();
myConnection.Open();
dataadapter.Fill(ds, "Authors_table");
myConnection.Close();

// I don't know what your primary key is, but you need to have one.
// I am assuming it's called "author_id".

DataColumn authorIdColumn = ds.Tables["Authors_table"].Columns["author_id"];
ds.Tables["Authors_table"].PrimaryKey = new[] { authorIdColumn };

// Get your second set of data
sql = "My second query, which also has the same primary key, but has more columns"
dataadapter = new SqlDataAdapter(sql, myConnection);
dataadapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
DataSet ds2 = ds.Clone();

myConnection.Open();
dataadapter.Fill(ds2, "Authors_table");
myConnection.Close();

// Now we use the DataSet.Merge method, which is very powerful. 
ds.Merge(ds2, false, MissingSchemaAction.AddWithKey);

dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";

您可能需要多次尝试:这只是大纲。在不了解您的数据以及到目前为止您所做的事情的情况下,很难知道您可能还需要调用哪些设置或方法。

【讨论】:

    【解决方案2】:

    试试这个。我一次运行了多个查询

    SqlDataAdapter adapter = new SqlDataAdapter(
      "SELECT * FROM Customers; SELECT * FROM Orders", connection);
    adapter.TableMappings.Add("Table", "Customer");
    adapter.TableMappings.Add("Table1", "Order");
    
    adapter.Fill(ds);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多