使用块作用域问题

问题描述

我正在即时学习视觉基础和面向对象编程。 这段代码查询结果显示到表单上的组合框...

Dim c = System.Configuration.ConfigurationManager.ConnectionStrings("db").ToString()
Dim daDogs As New sqlDataAdapter ("select dog_type from humane_society with(nolock)",c)
Dim dtdogs As New DataTable
dadogs.Fill(dtdogs)
cbodogs.DataSource = dtdogs
cbodogs.displayMember = "dog_type"

when I change it to use a Using block,the combo Box is blank
I think it is a scope issue,but I don't kNow how to fix it.  Any productive suggestions would be greatly appreciated.  Thanks!

Dim c = System.Configuration.ConfigurationManager.ConnectionStrings("db").ToString()
Using cDog As New sqlConnection(c)
      Using cmd As New sqlCommand("select dog_type from humane_society with(nolock)",cDog)
            cmd.CommandType = commandtype.Text
            Using daDogs As New sqlDataAdapter(cmd)
                  Using dtDogs As New Datatable`enter code here`
                        daDogs.Fill(dtDogs)
'                            MsgBox(dtMunic.Rows(500).Field(of string)(0))
                        cbodogs.DataSource = dtDogs
                        cbodogs.displayMember = "dog_type"
                  End Using
            End Using
      End Using
End Using

解决方法

不确定该消息框在您的代码中的作用。请记住,消息框会暂停代码,直到用户响应。您的连接,除其他外,在代码等待时打开。

在块中声明的项目的范围是该块是正确的。

我已将您的数据库代码与您的用户界面代码分开。

您可以通过添加逗号并在块中组合多个对象来节省使用块。行为相同,只是使代码更易于阅读。

Private ConStr As String = System.Configuration.ConfigurationManager.ConnectionStrings("db").ToString() '"Your connection string"

Private Function GetDogData() As DataTable
    Dim dt As New DataTable
    Using cDog As New SqlConnection(ConStr),cmd As New SqlCommand("select dog_type from humane_society with(nolock)",cDog)
        cDog.Open()
        Using reader = cmd.ExecuteReader
            dt.Load(reader)
        End Using
    End Using
    Return dt
End Function

Private Sub Button1_Click(sender As Object,e As EventArgs) Handles Button1.Click
    Dim dtDogs = GetDogData()
    cboDogs.DataSource = dtDogs
    cboDogs.DisplayMember = "dog_type"
End Sub