在vb.net windows窗体应用程序中使用适配器更新数据网格视图时出错

时间:2014-01-07 06:11:42

标签: vb.net datagridview

我已经从两个表填充了一个DataGridView。我正在使用Windows窗体

在页面加载事件中,我有以下代码:

Dim adapter As SqlDataAdapter
Dim bSource As BindingSource
Dim dt1 As DataTable

     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim con As SqlConnection = New SqlConnection("Data Source=SUPPORT2\SUPPORT2;Initial Catalog=Registry;Persist Security Info=True;User ID=sa;password=solutions") 'SET THE CONNECTION STRING
            con.Open()

            Dim cd As SqlCommandBuilder = New SqlCommandBuilder(adapter)
            adapter = New SqlDataAdapter("select c.cid,c.CompanyName,d.dtName,d.dtPhone,d.dtEmail  from CompanyMaster_tbl c join  DepartmentMaster_tbl d on c.Cid=d.cId", con)
            dt1 = New DataTable
            bSource = New BindingSource
            adapter.Fill(dt1)
            bSource.DataSource = dt1
            gv.DataSource = bSource
        End Sub

在更新按钮中单击我给出的代码如下:

Dim cid As Integer
        Dim cmpname As String
        Dim dtname As String
        Dim dtPhone As String
        Dim dtEmail As String
 Dim rv = DirectCast(bSource.Current, DataRowView)
        cid = rv.Row.Field(Of Integer)("Cid")
        cmpname = rv.Row.Field(Of String)("CompanyName")
        dtname = rv.Row.Field(Of String)("dtName")
        dtPhone = rv.Row.Field(Of String)("dtPhone")
        dtEmail = rv.Row.Field(Of String)("dtEmail")

        adapter.UpdateCommand.Parameters.AddWithValue("@Cid", cid)
        adapter.UpdateCommand.Parameters.AddWithValue("@CompanyName", cmpname)
        adapter.UpdateCommand.Parameters.AddWithValue("@dtName", dtname)
        adapter.UpdateCommand.Parameters.AddWithValue("@dtPhone", dtPhone)
        adapter.UpdateCommand.Parameters.AddWithValue("@dtEmail", dtEmail)
        adapter.UpdateCommand = New SqlCommand("UPDATE CompanyMaster_tbl SET CompanyName = @CompanyName, dtName = @dtName, dtPhone = @dtPhone, dtEmail = @dtEmail WHERE Cid = @Cid", con)

每当我在dataGridView中编辑某些内容并单击“更新”按钮时,我在此行中收到错误: adapter.UpdateCommand.Parameters.AddWithValue(&#34; @ Cid&#34;,cid) <登记/> 错误:对象引用未设置为对象的实例。

1 个答案:

答案 0 :(得分:0)

我认为您需要重新初始化适配器,将其添加到按钮单击代码:

    Adapter =  new SqlDataAdapter

编辑: 像这样改变你的代码:

    adapter.UpdateCommand = New SqlCommand("UPDATE CompanyMaster_tbl SET CompanyName = @CompanyName, dtName = @dtName, dtPhone = @dtPhone, dtEmail = @dtEmail WHERE Cid = @Cid", con)
    adapter.UpdateCommand.Parameters.AddWithValue("@Cid", cid)
    adapter.UpdateCommand.Parameters.AddWithValue("@CompanyName", cmpname)
    adapter.UpdateCommand.Parameters.AddWithValue("@dtName", dtname)
    adapter.UpdateCommand.Parameters.AddWithValue("@dtPhone", dtPhone)
    adapter.UpdateCommand.Parameters.AddWithValue("@dtEmail", dtEmail)
    adapter.UpdateCommand.ExecuteNonQuery()