Adding controls in gridview dynamically
I need to add controls to a GridView dynamically, so I added a PlaceHolder, but it it giving me an error.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
PlaceHolder plachldr = e.Row.FindControl开发者_StackOverflow("PlaceHolder2") as PlaceHolder;
Button btn = new Button() { ID = "btnShhow", Text = "Show" };
plachldr.Controls.Add(btn);
PlaceHolder placeholder = e.Row.FindControl("PlaceHolder1") as PlaceHolder;
TextBox txt1 = new TextBox();
placeholder.Controls.Add(txt1);
}
While adding the control to the PlaceHolder, is is giving me the following error:
Object reference not set to an instance of an object.
Here's the markup for my GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanging="GridView1_SelectedIndexChanging" onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Salary" HeaderText="Salary" />
<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You need to check plachldr or placeholder is null or not and also check for the RowType
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if( if (e.Row.RowType == DataControlRowType.DataRow)
{
PlaceHolder plachldr = e.Row.FindControl("PlaceHolder2") as PlaceHolder;
if(plachldr!=null)
{
Button btn = new Button() { ID = "btnShhow", Text = "Show" };
plachldr.Controls.Add(btn);
}
PlaceHolder placeholder = e.Row.FindControl("PlaceHolder1") as PlaceHolder;
if(placeholder!=null)
{
TextBox txt1 = new TextBox();
placeholder.Controls.Add(txt1);
}
}
}
精彩评论