在ASP.NET中,一個數據集可以包含多個數據表,本實例要實現的是兩個數據表合並到一個數據集中,即該數據集中包含原來兩個數據集中的所有表。
關鍵技術:
通過數據集的Merge方法可以將另外一個數據集、表集合或行數組的內容合並到當前數據集中。表的主鍵、表名稱、約束等因素都會影響合並數據集的效果。
Merge方法主要用於將指定的DataSet及其架構合並到當前DataSet中
public void Merge(DataSet dataSet);
代碼示例:
protected void Page_Load(object sender, EventArgs e) { DataSet dsSource = new DataSet(); //創建源數據集 DataSet dsTarget = new DataSet(); //創建目標數據集 string conStr = ConfigurationManager.ConnectionStrings["conStr"].ToString(); using (SqlConnection con = new SqlConnection(conStr))//創建數據連接 { //創建數據適配器 SqlDataAdapter sda = new SqlDataAdapter("select * from DictionaryType", con); sda.Fill(dsSource, "DictionaryType");//將字典類添加到源數據集 sda = new SqlDataAdapter("select * from DictionaryItem", con); sda.Fill(dsTarget, "DictionaryItem");//將字典值添加到目標數據集 } dsTarget.Merge(dsSource); //將源數據集的DictionaryType表合並到目標數據集中 GridView1.DataSource = dsTarget.Tables["DictionaryType"]; GridView1.DataBind(); }