【问题标题】:Adding controls in gridview dynamically在gridview中动态添加控件
【发布时间】:2013-10-04 19:44:08
【问题描述】:

我需要动态地将控件添加到 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>

【问题讨论】:

  • 您可能需要检查该行的类型 - 除非您在 GridView 中可以拥有的所有不同行类型中都有 PlaceHolder2。所以像这样: if (e.Row.RowType == DataControlRowType.DataRow) // 你的占位符代码在这里
  • @Pawan Bhise - 你的问题解决了吗

标签: c# asp.net gridview


【解决方案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);
    }
   }

}

【讨论】:

  • ​​ 占位符>
  • /ItemTemplate>
  • 在绑定方法中使用断点,并使用快速观察,并通过 e.Row.Controls —— 以查看占位符在哪里,它的 ID。以及如何获取占位符对象。
猜你喜欢
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-18
  • 2011-05-17
  • 2013-05-29
  • 2013-09-11
相关资源
最近更新 更多