Search code examples
c#asp.netaspxgridview

NullReferenceExecption while adding controls on DataBound of a gridview


This is my markup view

    <body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" DataKeyNames="SemesterID" DataSourceID="SqlDataSource1" >
            <Columns>
                <asp:BoundField DataField="SemesterID" HeaderText="SemesterID" InsertVisible="False" ReadOnly="True" SortExpression="SemesterID" />
                <asp:BoundField DataField="SemesterName" HeaderText="SemesterName" SortExpression="SemesterName" />
<asp:TemplateField>
                    <asp:PlaceHolder ID="pHldr" runat="server"></asp:PlaceHolder>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
        <asp:SqlDataSource ConnectionString="<%$ connectionStrings:MyConnection %>" ID="SqlDataSource1" runat="server" ProviderName="System.Data.SqlClient" SelectCommand="SELECT SemesterID, SemesterName FROM Semesters"></asp:SqlDataSource>
    </form>
</body>

This is my code behinde file

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        for (int i = 0; i < 3; i++)
        {
            PlaceHolder plHldr = e.Row.FindControl("pHldr") as PlaceHolder;
            CheckBox cbx = new CheckBox();

            plHldr.Controls.Add(cbx);//Here I get the exception
        }
    }

I would like to add controls such as checkboxes to the PlaceHolder but I get NullReferenceException in plHldr.Controls.Add(cbx);


Solution

  • Probably because you are not adressing the 1st line (with row index -1), which is the header. Try using e.Row.RowIndex to make sure you are not trying to cast controls from the header line:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex < 0) return;
    
        for (int i = 0; i < 3; i++)
        {
            PlaceHolder plHldr = e.Row.FindControl("pHldr") as PlaceHolder;
            CheckBox cbx = new CheckBox();
    
            plHldr.Controls.Add(cbx);//Here I get the exception
        }
    }