如何在vb.net中使用datagridview单元格作为WHERE子句语句

时间:2018-02-28 02:38:03

标签: vb.net

我在vb.net中有这个sql查询,我必须使用datagridview cell作为SELECT查询的参数。

这是代码:

Private Sub ClassSchedule()
        Dim strConn As String = My.Settings.SLCBRegistrarDBConnectionString
        Dim sqlCon As SqlConnection = New SqlConnection(strConn)
        Try
            sqlCon.Open()
            Dim QUERY As String
            QUERY = "SELECT CSchedClass.SCode as Code, ListofSubjects.[Course No.], ListofSubjects.[Descriptive Title], CSchedSubTD.TimeAndDay as Schedule, UtlyRoom.RoomName as Room, CSchedSubInstructor.NameInit as Instructor, CSchedSubDept.Dept, CSchedSubDept.Department " &
                    "FROM CSchedMAIN INNER JOIN CSchedClass ON CSchedMAIN.SubjCode = CSchedClass.id INNER JOIN  ListofSubjects ON CSchedClass.Subj = ListofSubjects.SubjectID INNER JOIN CSchedSubTD ON CSchedMAIN.TDCode = CSchedSubTD.TDCode INNER JOIN UtlyRoom ON CSchedMAIN.RoomID = UtlyRoom.RoomID INNER JOIN CSchedSubInstructor ON CSchedMAIN.InstID = CSchedSubInstructor.EmpID INNER JOIN  CSchedSubDept ON CSchedMAIN.Dept = CSchedSubDept.DeptID INNER JOIN SemesterList ON CSchedMAIN.SemID = SemesterList.SemID INNER JOIN SchoolYear ON CSchedMAIN.SYID = SchoolYear.[SY ID] INNER JOIN CSchedSubSect ON CSchedMAIN.Section = CSchedSubSect.id " &
                    "WHERE (CSchedSubSect.Section = '" & dgvSections.SelectedCells & "') AND  (SchoolYear.[School Year] = '" & cmbSY.Text & "') AND (SemesterList.Description = '" & cmbSemester.Text & "')"
            CMD = New SqlCommand(QUERY, sqlCon)
            CMD.ExecuteNonQuery()
            Adapter = New SqlDataAdapter(CMD)
            DT = New DataTable()
            Adapter.Fill(DT)
            dgvSchedule.DataSource = DT
            dgvSchedule.Columns(0).Width = 80
            dgvSchedule.Columns(1).Width = 120
            dgvSchedule.Columns(2).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            dgvSchedule.Columns(3).Width = 150
            dgvSchedule.Columns(4).Width = 80
            dgvSchedule.Columns(5).Width = 150
            dgvSchedule.Columns(6).Visible = False
            dgvSchedule.Columns(7).Visible = False
            sqlCon.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

问题是下面的语法不正确:

WHERE (CSchedSubSect.Section = '" & dgvSections.SelectedCells & "')

目标是当我点击datagridview" dgvSections"中的特定单元格时,上述查询应该执行并在datagridview" dgvSchedule"中加载数据。

请帮忙!

1 个答案:

答案 0 :(得分:0)

您需要参数化查询。

通过使用SelectedCells属性,我假设您还要检查多个值。如果是这种情况,那么您还需要将SQL语句从等号运算符更改为IN operator,这与使用OR作为多个值的逻辑等效。否则,如果您只想检查单个值,则需要将SelectedCells更改为CurrentCell

这是一个快速示例,展示了我的建议:

'Declare the object that will bind the DataGridView
Dim dt As DataTable = New DataTable

'Declare the connection object
Dim con As SqlConnection

'Wrap code in Try/Catch
Try
    'Set the connection object to a new instance
    'TODO: Change "My Connection String Here" with a valid connection string
    con = New SqlConnection("My Connection String Here")

    'Create a new instance of the command object
    Using cmd As SqlCommand = New SqlCommand("SELECT
                                                cschedclass.scode AS code,
                                                listofsubjects.[Course No.],
                                                listofsubjects.[Descriptive Title],
                                                cschedsubtd.timeandday AS schedule,
                                                utlyroom.roomname AS room,
                                                cschedsubinstructor.nameinit AS instructor,
                                                cschedsubdept.dept,
                                                cschedsubdept.department
                                            FROM cschedmain
                                            INNER JOIN cschedclass
                                                ON cschedmain.subjcode = cschedclass.id
                                            INNER JOIN listofsubjects
                                                ON cschedclass.subj = listofsubjects.subjectid
                                            INNER JOIN cschedsubtd
                                                ON cschedmain.tdcode = cschedsubtd.tdcode
                                            INNER JOIN utlyroom
                                                ON cschedmain.roomid = utlyroom.roomid
                                            INNER JOIN cschedsubinstructor
                                                ON cschedmain.instid = cschedsubinstructor.empid
                                            INNER JOIN cschedsubdept
                                                ON cschedmain.dept = cschedsubdept.deptid
                                            INNER JOIN semesterlist
                                                ON cschedmain.semid = semesterlist.semid
                                            INNER JOIN schoolyear
                                                ON cschedmain.syid = schoolyear.[SY ID]
                                            INNER JOIN cschedsubsect
                                                ON cschedmain.section = cschedsubsect.id
                                            WHERE 
                                                cschedsubsect.section    = @section AND
                                                schoolyear.[School Year] = @year AND
                                                semesterlist.description = @semester;", con)

        'Parameterize the query
        With cmd.Parameters
            .AddWithValue("@section", dgvSections.CurrentCell.Value.ToString)
            .AddWithValue("@year", cmbSY.Text)
            .AddWithValue("@semester", cmbSemester.Text)
        End With

        'Create a DataAdapter to fill the underlying DataTable with data
        Using adapter As SqlDataAdapter = New SqlDataAdapter(cmd)
            'Open the connection
            con.Open()

            'Use the Fill method to complete the operation
            adapter.Fill(dt)

            'Close the connection
            con.Close()
        End Using
    End Using
Catch ex As Exception
    'Display the error
    Console.WriteLine(ex.Message)
Finally
    'Check if the connection object was initialized
    If con IsNot Nothing Then
        If con.State = ConnectionState.Open Then
            'Close the connection if it was left open(exception thrown)
            con.Close()
        End If

        'Dispose of the connection object
        con.Dispose()
    End If
End Try

'Bind the table to the DataGridView
dgvSchedule.DataSource = dt