首页 > 解决方案 > 当我在 DataGrdiView 中添加一行时,我得到“连接没有关闭。连接的当前状态为打开”

问题描述

我有一个从 MS SQL Server 数据库填充的 datagridview(未绑定)。在从 DB 读取信息并将行添加到 datagridview1 的循环中,我收到此消息:“连接未关闭。连接的当前状态为打开”。

'这是代码

Private Sub ShowMSR_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim col As New CalendarColumn() With {.HeaderText = "ROS Date"}
            DataGridView1.Columns.Insert(5, col)
            Dim col_1 = New DataGridViewTextBoxColumn
            col_1.Name = "Date"
            DataGridView1.Columns(5).DefaultCellStyle.Format = "dd/MM/yyyy"

            Dim strsqlcommand As String = "SELECT * FROM MSR Where MSR_ID='" & MSRID & "'"
            Dim dr As SqlDataReader
            Dim sqlcommand = New SqlCommand(strsqlcommand, Form1.SQL_conn)


            Dim itemcode As String = ""
            Dim Desc As String = " "
            Dim qty As String = " "
            Dim un As String = " "
            Dim AC As String = ""
            Dim comm As String = ""

                 Dim rdate As Date
                strsqlcommand = "Select Item_Code, Quantity, Unit, Item_Description, AC_No, ROS_time, Coment_RO From ITEMS Where MSR_ID
= '" & MSRID & "'"
                sqlcommand.CommandText = strsqlcommand
                dr = sqlcommand.ExecuteReader()
                While dr.Read()
                    itemcode = dr(0).ToString
                    qty = dr(1).ToString
                    un = dr(2).ToString
                    Desc = dr(3).ToString
                    AC = dr(4).ToString
                    If IsDBNull(dr(5)) Then
                        rdate = CDate("1990/1/1")
                    Else
                        rdate = CDate(dr(5))
                    End If

                    comm = dr(6).ToString

                    Dim row As String() = New String() {itemcode, qty, un, Desc, AC, rdate, comm}
                    Me.DataGridView1.Rows.Add(row) '<---Here occur the problem 

                End While

                dr.Close()

                If (Form1.SQL_conn.State = ConnectionState.Open) Then Form1.SQL_conn.Close()

            Catch ex As Exception
              ' the exception is never triggered 
                MsgBox(ex.Message)
                If (Form1.SQL_conn.State = ConnectionState.Open) Then Form1.SQL_conn.Close()
            End Try
        End Sub

标签: vb.netdatagridviewsqlconnection

解决方案


推荐阅读