获取“对象引用未设置为对象实例”的错误。在gridView中显示数据时

时间:2015-03-29 02:51:52

标签: c# asp.net gridview

当用户点击“保存”时,我想将详细信息(从用户那里获取作为输入)添加到网格视图中。按钮。但是我没有将对象引用设置为对象的实例'点击“保存”时出错按钮。

以下是代码背后的代码,

 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();

    }

前端代码,

 <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>

有人可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

您的DataTable设置为null,因此您的DataRow

变化

DataTable rottCasetTbl = null;
DataRow dr = null; 

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();