使用DatagridView链接dataTable

时间:2012-11-18 10:55:02

标签: vb.net

我正在将DataTableDatagridView相关联,但是当我想创建新行时会出现错误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

1 个答案:

答案 0 :(得分: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的实例。