在gridview中添加新行时发​​生错误:System.NullReferenceException:对象引用未设置为对象的实例 [英] error when Adding new row in gridview: System.NullReferenceException: Object reference not set to an instance of an object

查看:54
本文介绍了在gridview中添加新行时发​​生错误:System.NullReferenceException:对象引用未设置为对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有错误:
System.NullReferenceException:对象引用未设置为对象的实例
当我尝试在网格视图中插入新行时.

下面是GridView:

Hi,

I have the error:
System.NullReferenceException: Object reference not set to an instance of an object
when i try to insert a new row in a grid view.

Below is the GridView:

<asp:GridView ID="gvTaskDetails" runat="server" AutoGenerateColumns="false" BackColor="LightGoldenrodYellow"

                    BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black"  GridLines="None" OnRowCommand="gvTaskDetails_rowCommand" 

                    OnRowDataBound="gvTaskDetails_RowDataBound" style="width: 970px">
                       <Columns>
                            <asp:TemplateField HeaderText="Name" ItemStyle-CssClass="Item_txtGrid" HeaderStyle-CssClass="Item_txtGrid">
                                <ItemTemplate>
                                    <asp:TextBox ID="txt_GridName" runat="server" Width="200px" Text='<%# Eval("NAME") %>' Visible="false" CssClass="textfield"></asp:TextBox>
                                    <asp:Label ID="lblGrdName" Width="200px" runat="server" CssClass="Item_txtGrid" Text='<%# Eval("NAME") %>'></asp:Label>
                                </ItemTemplate>
                           </asp:TemplateField>
                           <asp:TemplateField HeaderText="Description" ItemStyle-CssClass="Item_txtGrid" HeaderStyle-CssClass="Item_txtGrid">
                                <ItemTemplate>
                                    <asp:TextBox ID="txt_GridDesc" runat="server" Width="200px" Text='<%# Eval("DESCRIPTION") %>' Visible="false" CssClass="textfield"></asp:TextBox>
                                    <asp:Label ID="lblGrdDesc" Width="170px" runat="server" CssClass="Item_txtGrid" Text='<%# Eval("DESCRIPTION") %>'></asp:Label>
                                </ItemTemplate>
                           </asp:TemplateField>
                           <asp:TemplateField HeaderText="AssignedTo" ItemStyle-CssClass="Item_txtGrid" HeaderStyle-CssClass="Item_txtGrid">
                                <ItemTemplate>
                                    <asp:TextBox ID="txt_GridAssigned" runat="server" Width="200px" Text='<%# Eval("ASSIGNEDTO") %>' Visible="false" CssClass="textfield"></asp:TextBox>
                                     <asp:Label ID="lblGrdAssigned" Width="170px" runat="server" CssClass="Item_txtGrid" Text='<%# Eval("ASSIGNEDTO") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="StartDate" ItemStyle-CssClass="Item_txtGrid" HeaderStyle-CssClass="Item_txtGrid">
                                <ItemTemplate>
                                    <asp:TextBox ID="txt_GridStartDate" runat="server" Width="200px" Text='<%# Eval("STARTDATE") %>' Visible="false" CssClass="textfield"></asp:TextBox>
                                    <asp:Label ID="lblGrdStartDate" Width="170px" runat="server" CssClass="Item_txtGrid" Text='<%# Eval("STARTDATE") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="EndDate" ItemStyle-CssClass="Item_txtGrid" HeaderStyle-CssClass="Item_txtGrid">
                                <ItemTemplate>
                                    <asp:TextBox ID="txt_GridEndDate" runat="server" Width="200px" Text='<%# Eval("ENDDATE") %>' Visible="false" CssClass="textfield"></asp:TextBox>
                                    <asp:Label ID="lblGrdEndDate" Width="170px" runat="server" CssClass="Item_txtGrid" Text='<%# Eval("ENDDATE") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:ImageButton ID="lnkEdit" runat="server" AlternateText="Edit" CausesValidation="False" CommandName="EditClick" ImageUrl="~/Images/Proj_edit.gif" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
                                    <asp:ImageButton ID="lnkUpdate" runat="server" AlternateText="Update" CausesValidation="False" CommandName="UpdateClick" ImageUrl="~/Images/Proj_update.gif" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
                                    <asp:ImageButton ID="lnkDelete" runat="server" AlternateText="Delete" CausesValidation="False" CommandName="DeleteClick" ImageUrl="~/Images/Proj_delete.gif" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
                                </ItemTemplate>
                            </asp:TemplateField>
                                                                                                                                        
                        </Columns>
                        <AlternatingRowStyle BackColor="PaleGoldenrod" />
                        <FooterStyle BackColor="Tan" />
                        <HeaderStyle BackColor="Tan" Font-Bold="True" HorizontalAlign="Center" />
                        <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Right" />
                        <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
                    </asp:GridView>



下面是在btnAddRowToGrid_Click事件中调用的AddToGrid函数的代码:



Below is the code of AddToGrid function called in the event btnAddRowToGrid_Click:

private void AddToGrid()
    {
        
        try
        {
           DataTable dtable = new DataTable("ROW");
            
            if (Session["ShareHolderDetails"] != null)
            {
                dtable = (DataTable)Session["ShareHolderDetails"];
            }
            else
            {

                dtable.Columns.Add(new DataColumn("NAME"));
                dtable.Columns.Add(new DataColumn("DESCRIPTION"));
                dtable.Columns.Add(new DataColumn("ASSIGNEDTO"));
                dtable.Columns.Add(new DataColumn("STARTDATE"));
                dtable.Columns.Add(new DataColumn("ENDDATE"));

            }
            DataRow drow = dtable.NewRow();
            drow["NAME"] = string.Empty;
            drow["DESCRIPTION"] = string.Empty;
            drow["ASSIGNEDTO"] = string.Empty;
            drow["STARTDATE"] = string.Empty;
            drow["ENDDATE"] = string.Empty;

            dtable.Rows.Add(drow);


            gvTaskDetails.DataSource = dtable;
            gvTaskDetails.DataBind();
            foreach (GridViewRow gRow in gvTaskDetails.Rows)
            {
                
                Label lblGrdName = (Label)gRow.FindControl("lblGrdName");
                Label lblGrdDescription = (Label)gRow.FindControl("lblGrdDescription");
                Label lblGrdAssignedTo = (Label)gRow.FindControl("lblGrdAssignedTo");
                Label lblGrdStartDate = (Label)gRow.FindControl("lblGrdStartDate");
                Label lblGrdEndDate = (Label)gRow.FindControl("lblGrdEndDate");

                TextBox txtGrdName = (TextBox)gRow.FindControl("txtGrdName");
                TextBox txtGrdDescription = (TextBox)gRow.FindControl("txtGrdDescription");
                TextBox txtGrdAssignedTo = (TextBox)gRow.FindControl("txtGrdAssignedTo");
                TextBox txtGrdStartDate = (TextBox)gRow.FindControl("txtGrdStartDate");
                TextBox txtGrdEndDate = (TextBox)gRow.FindControl("txtGrdEndDate");

                ImageButton lnkEdit = (ImageButton)gRow.FindControl("lnkEdit");
                ImageButton lnkUpdate = (ImageButton)gRow.FindControl("lnkUpdate");
                ImageButton lnkDelete = (ImageButton)gRow.FindControl("lnkDelete");

                if (lblGrdName.Text.ToString() == string.Empty)
                {
                    txtGrdName.Visible = true;
                    txtGrdDescription.Visible = true;
                    txtGrdAssignedTo.Visible = true;
                    txtGrdStartDate.Visible = true;
                    txtGrdEndDate.Visible = true;

                    lblGrdName.Visible = false;
                    lblGrdDescription.Visible = false;
                    lblGrdAssignedTo.Visible = false;
                    lblGrdStartDate.Visible = false;
                    lblGrdEndDate.Visible = false;


                    lnkUpdate.Visible = true;
                    lnkEdit.Visible = false;
                    lnkDelete.Visible = true;
                }
            }
            Session["ShareHolderDetails"] = dtable;

        }
        catch (Exception ex)
        {
            throw new Exception(ex.ToString());
            
        }
       
    }



下面是在加载页面中显示网格视图的代码:



Below is the code of showing the grid view in the load page:

public void ShowGrid()
        {

            DataTable dtable = new DataTable("ROW");

            if (Session["ShareHolderDetails"] != null)
            {
                dtable = (DataTable)Session["ShareHolderDetails"];
            }
            else
            {
                dtable.Columns.Add(new DataColumn("NAME"));
                dtable.Columns.Add(new DataColumn("DESCRIPTION"));
                dtable.Columns.Add(new DataColumn("ASSIGNEDTO"));
                dtable.Columns.Add(new DataColumn("STARTDATE"));
                dtable.Columns.Add(new DataColumn("ENDDATE"));
            }
            gvTaskDetails.DataSource = dtable;
            gvTaskDetails.DataBind();
        }



Below is the code of the gridview RowDataBound:



Below is the code of the gridview RowDataBound:

protected void gvTaskDetails_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    ImageButton lnkDelete = (ImageButton)e.Row.FindControl("lnkDelete");
                    lnkDelete.Attributes.Add("onclick", "javascript:return confirm('Are you sure you want to delete the selected Task Details?');");

                    TextBox txtGrdName = (TextBox)e.Row.FindControl("txtGrdName");
                    TextBox txtGrdDescription = (TextBox)e.Row.FindControl("txtGrdDescription");
                    TextBox txtStartDate = (TextBox)e.Row.FindControl("txtStartDate");
                    TextBox txtEndDate = (TextBox)e.Row.FindControl("txtEndDate");
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }



Below is the code of the gridview rowCommand:



Below is the code of the gridview rowCommand:

protected void gvTaskDetails_rowCommand(object sender, GridViewCommandEventArgs e)
        {
            String ConnectionString = @"Data Source=SAFA-PC\SQLEXPRESS;Initial Catalog=ProjectMgnmt;Integrated Security=True";
            SqlConnection SqlConn = new SqlConnection(ConnectionString);
            try
            {
                SqlConn.Open();
                int Index = Convert.ToInt32(e.CommandArgument);
                GridViewRow gRow;
                gRow = gvTaskDetails.Rows[Index];

                Label lblGrdName = (Label)gRow.FindControl("lblGrdName");
                Label lblGrdDescription = (Label)gRow.FindControl("lblGrdDescription");
                Label lblGrdAssignedTo = (Label)gRow.FindControl("lblGrdAssignedTo");
                Label lblGrdStartDate = (Label)gRow.FindControl("lblGrdStartDate");
                Label lblGrdEndDate = (Label)gRow.FindControl("lblGrdEndDate");

                TextBox txtGrdName = (TextBox)gRow.FindControl("txtGrdName");
                TextBox txtGrdDescription = (TextBox)gRow.FindControl("txtGrdDescription");
                TextBox txtGrdAssignedTo = (TextBox)gRow.FindControl("txtGrdAssignedTo");
                TextBox txtGrdStartDate = (TextBox)gRow.FindControl("txtGrdStartDate");
                TextBox txtGrdEndDate = (TextBox)gRow.FindControl("txtGrdEndDate");

                ImageButton lnkEdit = (ImageButton)gRow.FindControl("lnkEdit");
                ImageButton lnkUpdate = (ImageButton)gRow.FindControl("lnkUpdate");
                ImageButton lnkDelete = (ImageButton)gRow.FindControl("lnkDelete");

                if (e.CommandName == "EditClick")
                {
                    txtGrdName.Visible = true;
                    txtGrdDescription.Visible = true;
                    txtGrdAssignedTo.Visible = true;
                    txtGrdStartDate.Visible = true;
                    txtGrdEndDate.Visible = true;



                    lblGrdName.Visible = false;
                    lblGrdDescription.Visible = false;
                    lblGrdAssignedTo.Visible = false;
                    lblGrdStartDate.Visible = false;
                    lblGrdEndDate.Visible = false;

                    lnkUpdate.Visible = true;
                    lnkEdit.Visible = false;
                    lnkDelete.Visible = false;

                }
                if (e.CommandName == "DeleteClick")
                {
                    DataTable dTable1 = (DataTable)Session["ShareHolderDetails"];
                    dTable1.Rows.RemoveAt(Index);
                    gvTaskDetails.DataSource = dTable1;
                    gvTaskDetails.DataBind();
                    Session["ShareHolderDetails"] = dTable1;
                }

                if (e.CommandName == "UpdateClick")
                {
                    txtGrdName.Visible = false;
                    txtGrdDescription.Visible = false;
                    txtGrdAssignedTo.Visible = false;
                    txtGrdStartDate.Visible = false;
                    txtGrdEndDate.Visible = false;

                    lblGrdName.Visible = true;
                    lblGrdDescription.Visible = true;
                    lblGrdAssignedTo.Visible = true;
                    lblGrdStartDate.Visible = true;
                    lblGrdEndDate.Visible = true;

                    lnkUpdate.Visible = false;
                    lnkEdit.Visible = true;
                    lnkDelete.Visible = true;

                   DataTable dTable1 = (DataTable)Session["ShareHolderDetails"];

                    dTable1.Rows[Index]["DESCRIPTION"] = txtGrdDescription.Text;
                    dTable1.Rows[Index]["ASSIGNEDTO"] = txtGrdAssignedTo.Text;
                    
                    dTable1.Rows[Index]["STARTDATE"] = txtGrdStartDate.Text;
                    dTable1.Rows[Index]["ENDDATE"] = txtGrdEndDate.Text;
                    
                    //Bind data to the Gridview
                    gvTaskDetails.DataSource = dTable1;
                    gvTaskDetails.DataBind();

                    //Store the datatable to Session
                    Session["ShareHolderDetails"] = dTable1;

                }

            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                SqlConn.Close();
            }
        }



请帮忙.. !!!
Thanks in advance



Please Help..!!!
Thanks in advance

推荐答案

ohhh am i stupid??
the error is in the gridview it self; the id of labels and textboxes are wrong: the correct one is:

ohhh am i stupid??
the error is in the gridview it self; the id of labels and textboxes are wrong: the correct one is:

<asp:gridview id="gvTaskDetails" runat="server" autogeneratecolumns="false" backcolor="LightGoldenrodYellow" xmlns:asp="#unknown">
                    BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black"  GridLines="None" OnRowCommand="gvTaskDetails_rowCommand" 
                    OnRowDataBound="gvTaskDetails_RowDataBound" style="width: 970px">
                       <columns>
                            <asp:templatefield headertext="Name" itemstyle-cssclass="Item_txtGrid" headerstyle-cssclass="Item_txtGrid">
                                <itemtemplate>
                                    <asp:textbox id="txtGrdName" runat="server" width="200px" text="<%# Eval("NAME") %>" visible="false" cssclass="textfield"></asp:textbox>
                                    <asp:label id="lblGrdName" width="200px" runat="server" cssclass="Item_txtGrid" text="<%# Eval("NAME") %>"></asp:label>
                                </itemtemplate>
                           </asp:templatefield>
                           <asp:templatefield headertext="Description" itemstyle-cssclass="Item_txtGrid" headerstyle-cssclass="Item_txtGrid">
                                <itemtemplate>
                                    <asp:textbox id="txtGrdDescription" runat="server" width="200px" text="<%# Eval("DESCRIPTION") %>" visible="false" cssclass="textfield"></asp:textbox>
                                    <asp:label id="lblGrdDescription" width="170px" runat="server" cssclass="Item_txtGrid" text="<%# Eval("DESCRIPTION") %>"></asp:label>
                                </itemtemplate>
                           </asp:templatefield>
                           <asp:templatefield headertext="AssignedTo" itemstyle-cssclass="Item_txtGrid" headerstyle-cssclass="Item_txtGrid">
                                <itemtemplate>
                                    <asp:textbox id="txtGrdAssignedTo" runat="server" width="200px" text="<%# Eval("ASSIGNEDTO") %>" visible="false" cssclass="textfield"></asp:textbox>
                                     <asp:label id="lblGrdAssignedTo" width="170px" runat="server" cssclass="Item_txtGrid" text="<%# Eval("ASSIGNEDTO") %>"></asp:label>
                                </itemtemplate>
                            </asp:templatefield>
                            <asp:templatefield headertext="StartDate" itemstyle-cssclass="Item_txtGrid" headerstyle-cssclass="Item_txtGrid">
                                <itemtemplate>
                                    <asp:textbox id="txtGrdStartDate" runat="server" width="200px" text="<%# Eval("STARTDATE") %>" visible="false" cssclass="textfield"></asp:textbox>
                                    <asp:label id="lblGrdStartDate" width="170px" runat="server" cssclass="Item_txtGrid" text="<%# Eval("STARTDATE") %>"></asp:label>
                                </itemtemplate>
                            </asp:templatefield>
                            <asp:templatefield headertext="EndDate" itemstyle-cssclass="Item_txtGrid" headerstyle-cssclass="Item_txtGrid">
                                <itemtemplate>
                                    <asp:textbox id="txtGrdEndDate" runat="server" width="200px" text="<%# Eval("ENDDATE") %>" visible="false" cssclass="textfield"></asp:textbox>
                                    <asp:label id="lblGrdEndDate" width="170px" runat="server" cssclass="Item_txtGrid" text="<%# Eval("ENDDATE") %>"></asp:label>
                                </itemtemplate>
                            </asp:templatefield>
                            <asp:templatefield>
                                <itemtemplate>
                                    <asp:imagebutton id="lnkEdit" runat="server" alternatetext="Edit" causesvalidation="False" commandname="EditClick" imageurl="~/Images/Proj_edit.gif" commandargument="<%# ((GridViewRow) Container).RowIndex %>" />
                                    <asp:imagebutton id="lnkUpdate" runat="server" alternatetext="Update" causesvalidation="False" commandname="UpdateClick" imageurl="~/Images/Proj_update.gif" commandargument="<%# ((GridViewRow) Container).RowIndex %>" />
                                    <asp:imagebutton id="lnkDelete" runat="server" alternatetext="Delete" causesvalidation="False" commandname="DeleteClick" imageurl="~/Images/Proj_delete.gif" commandargument="<%# ((GridViewRow) Container).RowIndex %>" />
                                </itemtemplate>
                            </asp:templatefield>
                                                                                                                                        
                        </columns>
                        <alternatingrowstyle backcolor="PaleGoldenrod" />
                        <footerstyle backcolor="Tan" />
                        <HeaderStyle BackColor="Tan" Font-Bold="True" HorizontalAlign="Center" />
                        <pagerstyle backcolor="PaleGoldenrod" forecolor="DarkSlateBlue" horizontalalign="Right" />
                        <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
                    </asp:gridview>


这篇关于在gridview中添加新行时发​​生错误:System.NullReferenceException:对象引用未设置为对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆