对象引用未设置为复选框中的对象实例

时间:2013-12-30 04:44:58

标签: c# asp.net nullreferenceexception

我正在使用gridview更新复选框。我没有将对象引用设置为对象的实例。

告诉我解决方案..

foreach (GridViewRow row in gvLeaves.Rows)
{

    if (((CheckBox)row.FindControl("chkSelect")) != null && ((CheckBox)row.FindControl("chkSelect")).Checked)
    {
        EP_LeaveManagementRow leaveStatusRow = db.EP_LeaveManagementCollection.GetRow("LeaveManagementID=" + gvLeaves.DataKeys[row.RowIndex]["LeaveManagementID"].ToString());
        if (leaveStatusRow != null)
        {
            leaveStatusRow.LeaveStatus = int.Parse(ddlStatus.SelectedValue.ToString());
            db.EP_LeaveManagementCollection.Update(leaveStatusRow);
            leaveStatusRow.ModifiedBy = logUser.UserType;
            leaveStatusRow.ModifiedDate = DateTime.Now;
        }
    }

ASPX

<asp:View ID="vwLeavesDetails" runat="server">
    <asp:GridView ID="gvLeaves" runat="server" Width="100%" AutoGenerateColumns="False"
        GridLines="Both" DataKeyNames="LeaveStatus" AllowPaging="true" PageSize="5"
         OnPageIndexChanging="gvLeaves_PageIndexChanging"
        OnRowCommand="gvLeaves_RowCommand" 
        onselectedindexchanged="gvLeaves_SelectedIndexChanged">
        <Columns>
            <asp:TemplateField>
                <HeaderTemplate>
                    <asp:CheckBox ID="chkBxHeader" onclick="javascript:HeaderClick(this);" runat="server"  TextAlign="Left"  />
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:CheckBox runat="server" ID="chkSelect"   TextAlign="Left" />
                </ItemTemplate>
                <HeaderStyle Width="5%" BorderWidth="1px"></HeaderStyle>
            </asp:TemplateField>

2 个答案:

答案 0 :(得分:0)

我的建议是使用断点,当你到达抛出异常的语句时,然后使用visual studio immediate window找出导致异常的语句。在即时窗口中,您可以执行每个部分语句并检查它是否返回null。

希望我帮忙!

答案 1 :(得分:0)

作为您提供的代码,我认为此行应为null

gvLeaves.DataKeys[row.RowIndex]["LeaveManagementID"]

因为在您的aspx代码中,您尚未将“LeaveManagementID”设置为 DataKeyName

你可以这样试试吗?

<asp:GridView ID="gvLeaves" runat="server" Width="100%" AutoGenerateColumns="False"
        GridLines="Both"
        DataKeyNames="LeaveManagementID,LeaveStatus" 
        AllowPaging="true" PageSize="5"
        OnPageIndexChanging="gvLeaves_PageIndexChanging"
        OnRowCommand="gvLeaves_RowCommand" 
        onselectedindexchanged="gvLeaves_SelectedIndexChanged">
        <Columns>
            <asp:TemplateField>
                <HeaderTemplate>
                    <asp:CheckBox ID="chkBxHeader" onclick="javascript:HeaderClick(this);" runat="server"  TextAlign="Left"  />
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:CheckBox runat="server" ID="chkSelect"   TextAlign="Left" />
                </ItemTemplate>
                <HeaderStyle Width="5%" BorderWidth="1px"></HeaderStyle>
            </asp:TemplateField>