VB.Net数据库项目之中,经常会用到关联查询的功能,例如下图所示:
点击左侧学生姓名,右侧显示从数据库里调入此学生的成绩。
步骤如下:
1、在页面加载时,分别通过dataset加载学生表Student与成绩表Score。
1 da = New SqlDataAdapter(S_User, conn) 2 da.Fill(dt, "Student") 3 DataGridView1.DataSource = dt.Tables("Student") 4 5 da = New SqlDataAdapter("select CstdNo as 学号,(select CcourseName from Course where CcourseNo=Score.CcourseNo) as 科目,cscore as 分数 from Score", conn) 6 da.Fill(dt, "Score")
此过程结束之后,dataset里面应该有两个表的完整信息dt.Tables("Student")与dt.Tables("Score")。
2、点击左侧列表具体行的时候,取得选择行的‘学号’。
1 Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick 2 '这里触发点击表体项目的事件 3 'MessageBox.Show(DataGridView1.CurrentRow.Cells(0).Value) 4 CstdNo = DataGridView1.CurrentRow.Cells(0).Value.ToString '取得当前行第一单元格的数据 5 End Sub
3、通过控件栏目,将BindingSource空间拖入表体,并通过BindingSource进行过滤。
1 Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick 2 '这里触发点击表体项目的事件 3 'MessageBox.Show(DataGridView1.CurrentRow.Cells(0).Value) '我 4 CstdNo = DataGridView1.CurrentRow.Cells(0).Value.ToString '取得当前行第一单元格的数据 5 6 BindingSource1.DataSource = dt.Tables("Score") '将dt里的表绑定到BindingSource1 7 BindingSource1.Filter = "学号=" & CstdNo '筛选之后再绑定 8 DataGridView2.DataSource = BindingSource1 9 10 End Sub
4、最后通过DataGridView2.DataSource = BindingSource1进行数据显示。