使用SqlDataAdapter填充数据视图时如何添加列

时间:2016-12-14 16:03:48

标签: c# sql datagridview sqldataadapter

我正在使用SQL来填充我的datagridview。我是这样做的:

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并粘贴选择。但我只想将数据添加到现有数据的右侧列中。

提前致谢

2 个答案:

答案 0 :(得分:0)

试试这个。我一次跑了多个查询

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

adapter.Fill(ds);

答案 1 :(得分:0)

这个要求听起来好像可以在Inner Join中使用的查询中使用SQL SqlDataAdapter来满足。如果您能够在匹配键上将两个数据源连接在一起,则可以简单地将数据拉下一次。但我会假设为什么那些不适合你的原因。

您实际上可以使用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";

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