动态添加gridview中的控件

时间:2011-09-08 06:23:40

标签: c# asp.net gridview

我需要动态地向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);
}

将控件添加到PlaceHolder时,是给我以下错误:

  

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

这是我的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 个答案:

答案 0 :(得分:1)

您需要检查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);
    }
   }

}