我收到了错误:
Fill: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
答案 0 :(得分:1)
而不是:
Dim con As SqlConnection
尝试添加New
:
Dim con As New SqlConnection("initial catalog=test;...")
但是,最佳做法是仅在您需要之前打开连接,然后立即关闭它。连接应该是局部变量in Using
blocks,而不是类变量!
答案 1 :(得分: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