【问题标题】:Checkboxes in DataGridDataGrid 中的复选框
【发布时间】:2015-04-03 16:59:44
【问题描述】:

我有一个 GridView,其中包含一个带有复选框的列。标题模板有一个复选框,用于选择列中的所有其他复选框。

当我勾选并执行事件时,我收到此错误:

Object reference not set to an instance of an object. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

在这一行:

ifchecked = DirectCast(item.FindControl("ckTransferItem"), CheckBox).Checked

数据网格代码:

<asp:DataGrid id="Dgcabinet" runat="server" CssClass="datagrids psLink" Width="100%" BorderStyle="None"
ForeColor="Transparent" GridLines="Horizontal" PagerStyle-Mode="NumericPages" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" PageSize="200">
    <ItemStyle CssClass="datagrids psLink"></ItemStyle>
    <HeaderStyle ForeColor="White" CssClass="datagridsHeader"></HeaderStyle>
    <Columns>
    <asp:BoundColumn Visible="False" DataField="file_pk"></asp:BoundColumn>
    <asp:BoundColumn DataField="file_pk" SortExpression="file_pk" HeaderText="&amp;nbsp;File Number">
    <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
    <ItemStyle HorizontalAlign="Center"></ItemStyle>
    </asp:BoundColumn>
    <asp:BoundColumn Visible="False" DataField="file_subject"></asp:BoundColumn>
    <asp:BoundColumn DataField="file_subject" SortExpression="file_subject" HeaderText="&amp;nbsp;File Name">
    <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
    <ItemStyle HorizontalAlign="Center"></ItemStyle>
    </asp:BoundColumn>
    <asp:BoundColumn Visible="False" DataField="cab_pk"></asp:BoundColumn>
    <asp:BoundColumn DataField="cab_pk" SortExpression="cab_pk" HeaderText="&amp;nbsp;Storage Number">
    <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
    <ItemStyle HorizontalAlign="Center"></ItemStyle>
    </asp:BoundColumn>
    <asp:BoundColumn Visible="False" DataField="comp_part"></asp:BoundColumn>
    <asp:BoundColumn DataField="comp_part" SortExpression="comp_part" HeaderText="&amp;nbsp;Compartment No.">
    <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
    <ItemStyle HorizontalAlign="Center"></ItemStyle>
    </asp:BoundColumn>
    <asp:BoundColumn Visible="False" DataField="dept_pk"></asp:BoundColumn>
    <asp:BoundColumn DataField="dept_code" SortExpression="dept_code" HeaderText="&amp;nbsp;Department Code">
    <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
    <ItemStyle HorizontalAlign="Center"></ItemStyle>
    </asp:BoundColumn>
    <asp:BoundColumn DataField="locationno" SortExpression="locationno" HeaderText="&amp;nbsp;Storage Location">
    <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
    <ItemStyle HorizontalAlign="Center"></ItemStyle>
    </asp:BoundColumn>
    <asp:TemplateColumn HeaderText="Tick to Transfer">
    <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
    <ItemStyle HorizontalAlign="Center"></ItemStyle>
    <ItemTemplate>
    <asp:CheckBox ID="ckTransferItem" Runat="server" AutoPostBack="false"></asp:CheckBox>
    </ItemTemplate>
    </asp:TemplateColumn>
    </Columns>
    <PagerStyle CssClass="datagridsFooter psLink" Mode="NumericPages"></PagerStyle>
</asp:DataGrid>

按钮事件处理程序:

  Private Sub btnbulktransfer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnbulktransfer.Click
    'get number of rows in datagrid
    Dim rowcount As Integer = Dgcabinet.Items.Count
    Dim itemrow As Integer = 0
    Dim item As DataGridItem
    Dim ifchecked As Boolean = False
    Dim getcompartment As Integer
    Dim getnewstate As Integer
    Dim getlocation As Integer
    Dim statetocomment As String
    Dim lbresult As Boolean = False
    Dim liUserRoleId As Integer
    Dim liUserId As Integer
    Dim switch As Boolean = False
    Dim linewdepartment As Integer
    Dim licurrentdepartment As Integer
    Dim lioldstates As Integer
    Dim listateid As Integer
    Dim lsImriehelRepository As String
    lioldstates = ddloldstates.SelectedValue


    licurrentdepartment = ddldepts.SelectedValue

    liUserRoleId = Convert.ToInt64(lcPrimitives.GetSessionCache("_USERROLE_ID"))
    liUserId = Convert.ToInt64(lcPrimitives.GetSessionCache("_USER_ID"))


    getlocation = ddllocation.SelectedValue
    getcompartment = ddlstorage.SelectedValue
    getnewstate = ddlnewstates.SelectedValue
    statetocomment = ddlnewstates.Items(ddlnewstates.SelectedIndex).Text
    linewdepartment = BLeRecords.getFileDepartment(getcompartment)
    listateid = ddldepts.SelectedValue

    'check if storage is in the imriehel repository
    lsImriehelRepository = [Global]._eRecordsPortalConstants.eRecordsCONST_ToImriehelRepository
    If linewdepartment = lsImriehelRepository Then
        linewdepartment = licurrentdepartment
    End If

    'check that all 'transfer to' dropdown options are selected
    If (getlocation = 0) Then
        lblError.Visible = True
        lblError.Text = "!Error. Please check location dropdown."
    ElseIf (getcompartment = 0) Then
        lblError.Visible = True
        lblError.Text = "!Error. Please check Storage dropdown."
    ElseIf (getnewstate = 0) Then
        lblError.Visible = True
        lblError.Text = "!Error. Please check Status dropdown."
    Else
        Dim fileIDs As ArrayList = New ArrayList
        Dim department As Integer
        ClearMessages()




        For itemrow = 0 To rowcount - 1

            Dim cb As CheckBox = item.Cells(11).FindControl("ckTransferItem")
            If cb.Checked Then
                ifchecked = True
            Else
                ifchecked = False
            End If


            department = Integer.Parse(item.Cells(8).Text())

            If ifchecked Then
                Dim filenumber As String = (item.Cells(0).Text())
                fileIDs.Add(filenumber)
                switch = True
            End If
        Next

        'check if tickbox are ticked. If not returns error.
        If switch = False Then
            lblError.Visible = True
            lblError.Text = "!Error. Please check tick box"
        Else
            lbresult = BLeRecords.updateBulkTransferBatch(fileIDs, getcompartment, linewdepartment, getnewstate, statetocomment, liUserId, listateid)

            If lbresult = True Then
                lblmessage.Text = "File transfer succesful"
                lblmessage.Visible = True
                DisplaySortedData("", lioldstates, licurrentdepartment, False)
            Else
                lblError.Visible = True
                lblError.Text = "!Error. File transfer Failed. Contact Administrator"
            End If
        End If

    End If
End Sub

这是我尝试过的,但我仍然得到同样的错误:

For Each dgItem As DataGridItem In Dgcabinet.Items

    If (dgItem.ItemType = ListItemType.Item) OrElse (dgItem.ItemType = ListItemType.AlternatingItem) Then
    
        ifchecked = DirectCast(dgItem.FindControl("ckTransferItem"), CheckBox).Checked
        department = Integer.Parse(dgItem.Cells(8).Text)

End If

Next

谁能解释一下原因?

如果复选框被选中,它应该设置为 True no?

【问题讨论】:

  • 请发布您负责查找和更新复选框状态的 vb.net 代码。以上代码中的item 是什么?从上面的代码我可以看出它无法找到控件并返回 null。
  • @CoderofCode 嗨,对不起.. 我编辑了主要问题以包含按钮的事件处理程序代码。 item 是一个数据网格项
  • 我该怎么做?当我选中一个框或全部选中时都会发生这种情况。

标签: asp.net vb.net checkbox datagrid


【解决方案1】:

在找到控制之前检查datagridItemType 项。在大多数可能的情况下,第一项或第一行始终是headertype,它会尝试在标题中找到该复选框,这就是它返回 null 的原因。

  If (item.ItemType ==  ListItemType.Item) || 
         (e.Item.ItemType == ListItemType.AlternatingItem) Then
        ifchecked = DirectCast(item.Cells[11].FindControl("ckTransferItem"), CheckBox).Checked
        //Your other code  
  End If 

阅读更多关于ItemType here的信息。

你也可以用 foreach 循环替换所有的 for 循环代码

     foreach(DataGridItem item in Dgcabinet.Items)
     {
        if((item.ItemType ==  ListItemType.Item) || 
           (e.Item.ItemType == ListItemType.AlternatingItem))
          {
             ifchecked = DirectCast(item.Cells[11].FindControl("ckTransferItem"), CheckBox).Checked
             department = int.Parse(item.Cells(8).Text())
             If ifchecked Then
                fileIDs.Add((item.Cells(0).Text()))
                switch = True
             End If
          }
     }

【讨论】:

  • 我仍然遇到同样的错误。请参阅我尝试过的代码的更新答案。
  • 尝试更新。只需确保 11 的 Cell[11] 是从 0 基本索引开始的列号 congaing 复选框。
  • 问题是没有找到checkbox控件。我试过Dim cb As CheckBox = item.FindControl("ckTransferItem"),cb 的值仍然是'Nothing'
  • 是的,我知道这就是为什么尝试Dim cb As CheckBox = item.Cells[11].FindControl("ckTransferItem")
  • 还是同样的错误。我尝试通过从 HTML 源代码中查找元素名称来调用它(因为我认为它在运行应用程序时会更改名称),但它仍然找不到它。也许这在使用 DataGrid 时是不可能的?
猜你喜欢
  • 2018-06-24
  • 1970-01-01
  • 2013-12-12
  • 2016-01-13
  • 2018-08-03
  • 2013-06-11
  • 2011-10-14
  • 2014-10-14
  • 1970-01-01
相关资源
最近更新 更多