2014-01-23 36 views
1

我想從SQL填充網格視圖中的數據。當我單擊按鈕並在網格視圖中填充數據時,我已被授予用戶訪問權限。但是我得到一個錯誤,那就是已經有一個與這個命令關聯的開放數據閱讀器,它必須先關閉。從sql填充數據到網格視圖

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     Try 
      If ComboBox2.Text = "-----select-----" Then 
       MsgBox("Please Select Region and Site ID", MsgBoxStyle.Critical, "failure") 
      Else 
       Button3.Show() 
       Button4.Show() 
       Button5.Show() 
       connection_open() 
       qry = "select * from LOG_ACCESS where ID='" & UCase(Environ$("Username")) & "' " 
       cmd1 = New SqlCommand(qry, cnn) 
       dr = cmd1.ExecuteReader 
       If dr.Read = True Then 
        MsgBox("login successful", MsgBoxStyle.Information, "login") 
        qry1 = "select * from SITE_DETAILS where Region = '" + ComboBox1.SelectedItem.ToString + "' And Site_ID = '" + ComboBox2.SelectedItem.ToString + "'" 
        adp = New SqlDataAdapter(qry1, cnn) 
        dr.Close() 
        adp.Fill(ds, "SITE_DETAILS") 
        'dr.Close() 
        DataGridView1.DataSource = ds 
        DataGridView1.DataMember = ds.Tables(0).ToString 
        DataGridView1.Hide() 
        'Me.Hide() 
        'dr.Close() 
        connection_close() 

       Else 
        MsgBox("Please Contact Administrator", MsgBoxStyle.Critical, "failure") 
        dr.Close() 
        connection_close() 
       End If 
      End If 
      dr.Close() 
      connection_close() 
     Catch ex As SqlException 
      MsgBox(ex.Message, MsgBoxStyle.Critical, "SqlError") 
     Catch ex As Exception 
      MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) 
     End Try 
    End Sub 

回答

0

在連接字符串設定MARS =「真」

嘗試,而不是dr = cmd1.ExecuteReader

dr = comm.ExecuteReader(CommandBehavior.CloseConnection) 
+0

嗨,我仍得到相同的錯誤。 – user2642374

+0

感謝您的回覆nagaraj。我已根據您的建議嘗試過。但我仍然得到相同的錯誤 – user2642374

0

我不知道這個問題是不是出了什麼事情在你的OPEN_CONNECTION方法這一點。

通常,當我看到填充的數據網格時,它是在使用語句的上下文中...(使用sql SQLConnection ...)您是否嘗試過這種方法?

這樣,您的連接只能使用使用範圍的大括號打開......一旦塊完成,它將自動處理,因此您不需要在if邏輯中使用所有這些.close。

這裏是你可能會發現有用的鏈接: http://www.canofcode.co.uk/software/c-sharp-using-statement/