2008年5月21日 星期三

Window Form主副檔連動之技巧

Dim dsReason As New DataSet
Dim db As New dbAccess '資料存取類別
Dim SQL As String

'Grid欄位不自動產生
grdReasonM.AutoGenerateColumns = False
grdReasonD.AutoGenerateColumns = False

'取出主檔
SQL = "select distinct tblno1,tblnm1 from Jokendt where tblcd='TBLCD' order by tblno1"
'將取出之資料存致DataSet
dsReason = db.GetData(SQL, "ReasonM")
'設定主檔之BindingSource元件之資料成員
bsReasonM.DataMember = "ReasonM"
bsReasonM.DataSource = dsReason
'將顯示主檔資料之DataGrid繫結至主檔之BindingSource
grdReasonM.DataSource = bsReasonM

'取出副檔
SQL = "select distinct tblno1,tblno2,tblnm2 from Jokendt where tblcd='TBLCD' order by tblno2"
dsReason = db.GetData(SQL, "ReasonD")

'設定主副檔之關聯欄位
Dim col_M As DataColumn
Dim col_D As DataColumn
col_M = dsReason.Tables("ReasonM").Columns("tblno1")
col_D = dsReason.Tables("ReasonD").Columns("tblno1")
'設定主婦檔之關聯物件(DataRelation)
Dim rel As New DataRelation("reason", col_M, col_D)
dsReason.Relations.Add(rel)

'設定副檔之BindingSource元件之資料成員
bsReasonD.DataMember = "reason" 'DataMember設關聯名稱
bsReasonD.DataSource = bsReasonM 'DataSource設主之之Source

'將顯示副檔資料之DataGrid繫結至主檔之BindingSource
grdReasonD.DataSource = bsReasonD

OK....當主檔之DataGrid(grdReasonM)資料變動,副檔之DataGrid(grdReasonD)會自動跟著一起連動

'Tips==>如何取得副檔當前被選取Row之資料
Dim ReasonM As String
Dim ReasonD As String
'取得主檔目前被選取之Row之某欄位(tblno1)的值
ReasonM = dsReason.Tables("ReasonM").Rows(bsReasonM.Position)("tblno1").ToString.Trim()

'要取得副檔當前選取之Row需透過主檔之GetChildRows方法取得副檔關聯之Rows,在依其副檔之RowIndex取得當前被選取之Row
'ReasonD = dsReason.Tables("ReasonM").Rows(bsReasonM.Position).GetChildRows("reason")(bsReasonD.Position)("tblno2").ToString.Trim()
'上行程式可分成2行來寫,閱讀性較高
'A.取出主檔當前被選取之Row
Dim dr As DataRow = dsReason.Tables("ReasonM").Rows(bsReasonM.Position)
'B.依關聯物件取出副檔之Rows,再依副檔之Rowindex取得副檔當前被選取之Row
ReasonD = dr.GetChildRows("reason")(bsReasonD.Position)("tblno2").ToString.Trim()

沒有留言: