-1

我得到了错误:

填充:SelectCommand.Connection 属性尚未初始化。

我认为这是因为我声明我的数据集不是在里面private sub 而是在public class......但是我需要在程序中多次使用不同的数据集private sub......我应该如何定义它?非常感谢。

Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim con As SqlConnection
Dim strsql As String
Dim da As New SqlDataAdapter(strsql, con)
Dim ds As New DataSet()
Dim strcon As String
Dim newmode As Boolean
Dim newrow As DataRow
Dim cb As SqlCommandBuilder

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    newmode = False
    'Dim con As SqlConnection
    'Dim strsql As String
    con = New SqlConnection("initial catalog=test;data source=nazi;integrated security=sspi;")
    strsql = "select*from table_1"
    con.Open()
    'Dim da As New SqlDataAdapter(strsql, con)
    'Dim ds As New DataSet()

    da.Fill(ds, "dd")

    TextBox1.DataBindings.Add(New Binding("text", ds, "dd.tel"))
    TextBox2.DataBindings.Add(New Binding("text", ds, "dd.nam"))
    TextBox3.DataBindings.Add(New Binding("text", ds, "dd.address"))
    da.update(ds, "dd")
    con.Close()
End Sub

Private Sub empty()
    textrecord.text = ""
    TextBox1.text = ""
    TextBox2.text = ""
    TextBox3.text = ""
    TextBox4.text = ""
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    newrow = ds.Tables("dd").NewRow
    newmode = True
    textrecord.BackColor = Color.Red
    textrecord.Text = "new record"
    MsgBox("enter new record and press save")
    Call empty()
End Sub

End Class
4

2 回答 2

1

代替:

Dim con As SqlConnection

尝试添加New

Dim con As New SqlConnection("initial catalog=test;...")

但是,最佳做法是仅在需要之前打开连接,然后立即关闭它。连接应该是块中的局部变量Using不是类变量!

于 2012-07-10T06:02:27.763 回答
0

您在此行的全局级别创建 DataAdapter

Dim da As New SqlDataAdapter(strsql, con) 

但是此时您的 strsql 是空的,如果您之后更改它,它不会在 dataadatpter 内部更改,因此会出现错误消息。

如果您坚持保留所有全局变量(并且正如@Andomar 在答案中指出的那样,这被认为是一种不好的做法),那么您应该确保在使用之前使用正确的 sqlstring 创建 DataAdapter:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load     
    newmode = False     
    con = New SqlConnection("initial catalog=test;data source=nazi;integrated security=sspi;") 
    strsql = "select*from table_1"     
    con.Open()     
    da = New SqlDataAdapter(strsql, con) '<- added this line here '  
    da.Fill(ds, "dd")      
    ....
    con.Close() 
End Sub 
于 2012-07-10T07:30:38.347 回答