1

I'm linking DataTable with DatagridView but when I want to make new row gives me an error System.NullReferenceException was unhandled by user code . Object reference not set to an instance of an object.


Imports System.Data

Partial Class DataAssembly_SearchCentral
Inherits System.Web.UI.Page

Dim tblresult As DataTable
Dim drCurrent As DataRow
Dim dsdata As New DataSet()

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If IsPostBack Then
        Exit Sub
    End If
    If ResultGV.Rows.Count = 0 Then

        tblresult = New DataTable("tblresult")
        Dim column As DataColumn

        column = New DataColumn()
        column.DataType = System.Type.GetType("System.String")
        column.ColumnName = "Payeer"
        column.AutoIncrement = False
        column.Caption = "Payeer"
        column.ReadOnly = False
        column.Unique = False

        tblresult.Columns.Add(column)

        column = New DataColumn()
        column.DataType = System.Type.GetType("System.String")
        column.ColumnName = "Office"
        column.AutoIncrement = False
        column.Caption = "Office"
        column.ReadOnly = False
        column.Unique = False

        tblresult.Columns.Add(column)

        dsdata.Tables.Add(tblresult)

    End If

End Sub
Protected Sub Result_btn_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles Result_btn.Click

    drCurrent = tblresult.NewRow()
    drCurrent("Payeer") = MasName_txt0.Text
    drCurrent("Office") = ddl_office.SelectedItem.Text
    tblresult.Rows.Add(drCurrent)


    dsdata.Tables.Add(tblresult)
    ResultGV.DataSource = dsdata.Tables("tblresult")

    ResultGV.DataBind()

End Sub

End Class
4

1 回答 1

0

tblresult当您尝试在 中访问它时不存在Result_btn_Click()

看看你的Page_Load()方法:

If IsPostBack Then
    Exit Sub ' <-- This gets called and the code below won't execute.
             '     Therefore tblresult doesn't exist in the click handler
End If

If ResultGV.Rows.Count = 0 Then

    tblresult = New DataTable("tblresult")
    ' ...

End If

tblresult如果它不是回发,您只创建一个实例。另一方面,无论何时触发事件处理程序,请求都是回发。确保tblresult在尝试添加新行之前创建一个实例。

于 2012-11-18T11:10:59.777 回答