Adding controls in gridview dynamically

余生颓废 提交于 2019-12-24 03:50:28

问题


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

回答1:


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

}


来源:https://stackoverflow.com/questions/7343943/adding-controls-in-gridview-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!