-2

I want to add the details (which are getting from the user as inputs) in to a grid view when user clicks the 'Save' button. But I'm getting 'Object reference not set to an instance of an object' error when i click the 'save' button.

Here is the code in code behind,

 protected void btnSave_Click(object sender, EventArgs e)
    {
        string rootCaseID = txtRootCaseID.Text;
        string root = txtRoot.Text;
        string description = txtDes.Text;

        DataTable rottCasetTbl = null;
        DataRow dr = null; ;
        dr["id"] = txtRootCaseID.Text;
        dr["root"] = txtRoot.Text;
        dr["description"] = txtDes.Text;
        rottCasetTbl.Rows.Add(dr);
        grdrootCase.DataSource = rottCasetTbl;
        grdrootCase.DataBind();

    }

Front end code,

 <tr>
    <td align="center">
          <asp:GridView ID="grdrootCase" runat="server" ShowHeaderWhenEmpty="true" 
                            EmptyDataText="No Records Found" AutoGenerateColumns="False" 
                            CellPadding="4" ForeColor="#333333" 
                            GridLines="None" Font-Size="Small" 
                            Width="95%">
                            <AlternatingRowStyle BackColor="White" />

                            <Columns>

                                <asp:BoundField HeaderText="Root Case ID" DataField="id" />
                                <asp:BoundField HeaderText="Root" DataField="root" />
                                <asp:BoundField HeaderText="Description" DataField="description" />
                            </Columns>

                            <EditRowStyle BackColor="#2461BF" />
                            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                            <RowStyle BackColor="#EFF3FB" />
                            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                            <SortedAscendingCellStyle BackColor="#F5F7FB" />
                            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                            <SortedDescendingCellStyle BackColor="#E9EBEF" />
                            <SortedDescendingHeaderStyle BackColor="#4870BE" />
                        </asp:GridView>

        </td>
    </tr>

Can someone help me with this issue.

Madushi
  • 1
  • 2
  • 5

1 Answers1

2

Your DataTable is set to null so is your DataRow

change

DataTable rottCasetTbl = null;
DataRow dr = null; 

to

DataTable rottCasetTbl = new  DataTable();
//add the columns
rottCasetTbl.Columns.Add("id", typeof(String));
rottCasetTbl.Columns.Add("root", typeof(String));
rottCasetTbl.Columns.Add("description", typeof(String));
DataRow dr = rottCasetTbl.NewRow();
Xi Sigma
  • 2,292
  • 2
  • 13
  • 16