假设有n个按钮和一个datagridview。
我拖动包含n个表的数据集,因此创建具有相同连接字符串的n个tableadapter。我想点击每个按钮分别显示每个tableadapter中的每个表。
我认为这是一个坏主意。
我应该以编程方式创建tableadapter而不是将控件拖到窗体中吗?
答案 0 :(得分:1)
我刚为别人写了这段代码:
//class variable:
DataSet ds = new DataSet();
//fill dataset in some of your method:
using(SqlConnection conn = new SqlConnection("connString"))
{
DataTable table1 = new DataTable("People");
DataTable table2 = new DataTable("Cars");
ds.Tables.Add(table1);
ds.Tables.Add(table2);
string query1 = @"SELECT * FROM People";
string query2 = @"SELECT * FROM Cars";
string[] queries = { query1, query2 };
for(int i = 0; i < queries.Length; i++)
{
using(SqlDataAdapter da = new SqlDataAdapter(queries[i], conn))
da.Fill(ds.Tables[i]);
}
}
//now bind tables to your button click events (this is example for Cars):
void button1_Click()
{
dataGridView1.DataSource = null;
dataGridView1.DataSource = ds.Tables["Cars"].DefaultView;
//do the same for table "People" in some other button click event
}