Ok I have seen to many post about this and nothing work for me, I just do not get it. I have a simple datagrid which i want to add rows, NOTE: this datagrid have no relation with database so everything has to be done datatable or arraylist whatever you want to help me.

Im going to post a few lines of what i have so far.

<asp:DataGrid ID="dgHistoric" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnItemCommand="InsertSaveHist" >
                        <Columns>
                            <asp:TemplateColumn HeaderText="OSR">
                                <ItemTemplate>
                                    <asp:Label ID="txtHisOsr" runat="server" Width="25" Text='<% #DataBinder.Eval(Container.DataItem, "Opsheetrev").ToString() %>'></asp:Label>
                                </ItemTemplate>
                                <FooterTemplate>
                                    <asp:TextBox ID="txtFHisOsr" runat="server" Width="25"></asp:TextBox>
                                </FooterTemplate>
                            </asp:TemplateColumn>
                             <asp:TemplateColumn HeaderText="Eng Dwg Rev.">
                                <ItemTemplate>
                                    <asp:Label ID="txtHisEdr" runat="server" Width="25" Text='<% #DataBinder.Eval(Container.DataItem, "Engdwgrev").ToString() %>'></asp:Label>
                                </ItemTemplate>
                                <FooterTemplate>
                                    <asp:TextBox ID="txtFHisEdr" runat="server" Width="25"></asp:TextBox>
                                </FooterTemplate>
                            </asp:TemplateColumn>
 <asp:TemplateColumn>
                                <FooterTemplate>
                                    <asp:Button ID="btnAddHis" runat="server" Text="Add" CommandName="InsertHist" />
                                </FooterTemplate>
                            </asp:TemplateColumn>
                        </Columns>
                    </asp:DataGrid>

now in the load page function i have this because i want the first row blank.

DataTable dtOpe = new DataTable();
                DataSet dsComp = new DataSet();
       
                DataRow drOpe;
                dtOpe.Columns.Add("Opsheetrev");
                dtOpe.Columns.Add("Engdwgrev");
                drOpe = dtOpe.NewRow();
                drOpe[0] = "";
                drOpe[1] = "";
                dtOpe.Rows.Add(drOpe);
                dsComp.Tables.Add(dtOpe);
                dgHistoric.DataSource = dsComp;
                dgHistoric.DataBind();

and finally the insert function

DataSet dsComp = new DataSet();
                DataTable dt = (DataTable)dgHistoric.DataSource;
                
                DataRow dr = dt.NewRow();
                string osr = ((TextBox)e.Item.Cells[0].FindControl("txtFHisOsr")).Text;
                string edr = ((TextBox)e.Item.Cells[1].FindControl("txtFHisEdr")).Text;
             
                dr[0] = osr;
                dr[1] = edr;
                dt.Rows.Add(dr);
                dsComp.Tables.Add(dt);
                dgHistoric.DataSource = dt;
                dgHistoric.DataBind();

an error is generated in this point DataRow dr = dt.NewRow(); saying NullReferenceException was unhandled by user code.

thanks in advance for any help.

Dani AI

Generated

The NullReferenceException at dt.NewRow() means dt is null when the Insert handler runs. That happens because the grid's DataSource is not persisted across postbacks — casting dgHistoric.DataSource back to a DataTable on postback will often return null. The root causes here are (a) binding a DataSet instead of the actual DataTable and (b) not keeping the DataTable alive between postbacks.

As warned, you can't safely cast a DataSet to a DataTable. As pointed out, bind the grid to dsComp.Tables[0] (the real table). And as suggested, keep the table in Session or ViewState so it exists when the Add button is clicked. Looks like @adatapost's suggestion ultimately fixed the problem for .

A simple, safe pattern is: on initial load create the DataTable, save it to ViewState or Session, bind the grid; on Add retrieve the table from ViewState/Session, add the new row, save it back, then rebind. Example outline:

DataTable dt = ViewState["HistoricDT"] as DataTable;
if (dt == null) { /* create columns and initial blank row */ }
dt.Rows.Add(newRow);
ViewState["HistoricDT"] = dt;
dgHistoric.DataSource = dt;
dgHistoric.DataBind();

Troubleshooting notes: use e.Item.FindControl("txtFHisOsr") (find by ID on the Footer item) rather than relying on cell indexes; verify the Button has the correct CommandName and the grid's OnItemCommand is wired; and weigh tradeoffs: ViewState bloats page size, Session uses server memory. For newer projects consider GridView or a client-side grid for better maintainability.

Recommended Answers

All 4 Replies

you are trying to cast dataset to datatable, my suggestion is to get rid of dataset object as you can set datatable object directly as a datasource, and try to do everything without using any datasets here.

try to change
dgHistoric.DataSource = dsComp;
to
dgHistoric.DataSource = dsComp.Tables[0];

if there is only a table in the dataset.

hope it help.

This post should moved to ASP.NET. Use Session or ViewState

Code of Page_load

if (IsPostBack == false)
        {
            DataTable dtOpe = new DataTable();
            DataSet dsComp = new DataSet();

            DataRow drOpe;
            dtOpe.Columns.Add("Opsheetrev");
            dtOpe.Columns.Add("Engdwgrev");
            drOpe = dtOpe.NewRow();
            drOpe[0] = "";
            drOpe[1] = "";
            dtOpe.Rows.Add(drOpe);
            dsComp.Tables.Add(dtOpe);
            dgHistoric.DataSource = dsComp.Tables[0];
            dgHistoric.DataBind();
            Session["dt"] = dtOpe;
        }

Code of Insert Method

DataTable dt = (DataTable)Session["dt"];
        DataRow dr = dt.NewRow();
        string osr = ((TextBox)e.Item.Cells[0].FindControl("txtFHisOsr")).Text;
        string edr = ((TextBox)e.Item.Cells[1].FindControl("txtFHisEdr")).Text;

        dr[0] = osr;
        dr[1] = edr;
        dt.Rows.Add(dr);
         
        dgHistoric.DataSource = dt;
        dgHistoric.DataBind();

I tried the first two suggestions but got the same error, the third one adatapost resolved my issue thanks all.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.