通过DataRelation将DataTable建立关系,通过两个GridView显示主从表数据

  DataRelation对象的最主要的用途是查找不同DataTable对象中的数据。通过DataRow对象的GetChildRows,GetParentRow和GetParentRows方法提供的。GetChildRows方法将相关数据作为一个DataRow对象数组返回。

     通过GridView的SelectedIndexChanging事件判断出所对应的datarow,通过对datarow调用GetChildRows方法,返回DataRow对象数组,再经过遍历加载到泛型集合中去,最后将GridView的datasource与泛型集合绑定。

     以下代码即为简单的Demo:

private string connString = ConfigurationManager.ConnectionStrings["ADOConnectionString"].ToString();
        SQLHelper sqlHelper = new SQLHelper();
        DataRelation rel;
        DataSet ds;
        DataRow rowselect;

        protected void Page_Load(object sender, EventArgs e)
        {
                SetDataSource();
        }
        public void SetDataSource()
        {
            ds = new DataSet();
            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlDataAdapter mainTable = new SqlDataAdapter("select * from Test_Model", conn);
                SqlDataAdapter detailTable = new SqlDataAdapter("select * from Test_Item", conn);
                mainTable.Fill(ds, "Test_Model");
                detailTable.Fill(ds, "Test_Item");

                rel = ds.Relations.Add("Model_Item", ds.Tables["Test_Model"].Columns["ModelCode"], ds.Tables["Test_Item"].Columns["ModelCode"]);
                GridView1.DataSource = ds.Tables["Test_Model"].DefaultView;
                GridView1.DataBind();

            }
        }

        protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        { 
            GridViewRow gvRow=GridView1.Rows[e.NewSelectedIndex];
            txtModelCode.Text=gvRow.Cells[1].Text;
            btnCommand.Text = "新建";
            txtItemCode.Text = string.Empty;
            txtItemDesc.Text = string.Empty;

            rowselect = ds.Tables["Test_Model"].Rows[e.NewSelectedIndex];

            IList<TestItem> testItems=new List<TestItem>();
            foreach (DataRow  row in rowselect.GetChildRows(rel))
            {
                TestItem testItem = new TestItem(row[0].ToString(),row[1].ToString(),row[2].ToString());
                testItems.Add(testItem);
            }
            GridView2.DataSource = testItems;
            GridView2.DataBind();
            
        }

        protected void GridView2_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            GridViewRow gvRow = GridView2.Rows[e.NewSelectedIndex];
            txtModelCode.Text = gvRow.Cells[1].Text;
            txtItemCode.Text = gvRow.Cells[2].Text;
            txtItemDesc.Text = gvRow.Cells[3].Text;
            btnCommand.Text = "保存";
        }

  

posted @ 2011-07-21 16:12  TonnyGu  阅读(1871)  评论(0编辑  收藏  举报