积极答复者
请教 DataAdapter 更新数据问题,更新数据时报错(vb.net)

问题
-
大家好 请帮我看看这段代码 执行 dadapter.Update(ds, "Writer")时报错 错误提示“ConnectionString 属性尚未初始化” 代码如下
各位高手帮忙看看是怎么回事 先谢谢了
Public Class Form1 Public dbconnection As SqlClient.SqlConnection Public dbconnectionstring As String Dim dadapter As SqlDataAdapter Dim dtable As DataTable Dim ds As DataSet Dim selectstr As String Dim selectdbcommand As SqlCommand Public Sub opendbconnection() dbconnectionstring = "Data Source=LT;Database=sxfx;Integrated Security=SSPI;Persist Security Info=False" dbconnection = New SqlClient.SqlConnection(dbconnectionstring) Try dbconnection.Open() Catch ex As Exception MsgBox(ex.Message.ToString) End Try End Sub Public Sub closedbconnection() dbconnection.Dispose() dbconnection.Close() End Sub Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load opendbconnection() selectstr = "select name from Writer" selectdbcommand = New SqlClient.SqlCommand(selectstr, dbconnection) dadapter = New SqlDataAdapter(selectdbcommand) dtable = New DataTable("Writer") ds = New DataSet dadapter.Fill(ds, "Writer") DataGridView.DataSource = ds.Tables("Writer") closedbconnection() End Sub Private Sub BtUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtUpdate.Click opendbconnection() Dim scb As SqlCommandBuilder = New SqlCommandBuilder(dadapter) dadapter.Update(ds, "Writer") closedbconnection() End Sub End Class
昨夜西风凋碧树,独上高楼,望尽天涯路!
答案
-
你好!
建议你使用 using 的方式。DataAdapter 的 Fill 方法会自动打开与关闭连接,这里无需其它代码操作。
using (SqlDataAdapter da = new SqlDataAdapter("select name from Writer" , "Data Source=LT;Database=sxfx;Integrated Security=SSPI;Persist Security Info=False")) { DataSet ds = new DataSet(); da.Fill(ds); DataGridView.DataSource = ds.Tables[0]; }
知识改变命运,奋斗成就人生!- 已标记为答案 Mog Liang 2010年4月20日 6:48
全部回复
-
你好!
建议你使用 using 的方式。DataAdapter 的 Fill 方法会自动打开与关闭连接,这里无需其它代码操作。
using (SqlDataAdapter da = new SqlDataAdapter("select name from Writer" , "Data Source=LT;Database=sxfx;Integrated Security=SSPI;Persist Security Info=False")) { DataSet ds = new DataSet(); da.Fill(ds); DataGridView.DataSource = ds.Tables[0]; }
知识改变命运,奋斗成就人生!- 已标记为答案 Mog Liang 2010年4月20日 6:48