动态地在gridview中添加控件
我需要动态地将控件添加到GridView,所以我添加了一个PlaceHolder,但它给了我一个错误。动态地在gridview中添加控件
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);
}
同时加入了控制占位符,则是给我下面的错误:
Object reference not set to an instance of an object.
这里的标记为我的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>
您需要检查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);
}
}
}
是的,它显示两个占位符都是null.Now该怎么办? –
你可以帮我一些工作代码。 –
@Pawan Bhise - 你能PLZ发布网格代码 –
您可能需要检查行的类型 - 除非您在GridView中的所有不同行类型中都有PlaceHolder2。所以像这样:if(e.RowType == DataControlRowType.DataRow)//你的占位符代码在这里 –
@Pawan Bhise - 你问题解决 –