动态地在gridview中添加控件

本文关键字:添加 控件 gridview 动态 | 更新日期: 2023-09-27 18:07:51

我需要动态地添加控件到GridView,所以我添加了一个PlaceHolder,但是它给了我一个错误。

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

当控件添加到占位符时,它会给我以下错误:

未设置为对象实例的对象引用

这是我的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>

动态地在gridview中添加控件

您需要检查plachldr或占位符是否为空,并检查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);
    }
   }
}