[英]Dynamically adding child controls to listview control in ASP.NET C# from code behind file
This is my code behind the file: 这是文件后面的代码:
ImageButton img = new ImageButton();
img.AlternateText = "<%# Eval(\"colA\") %>";
img.ImageUrl = "~/img.png";
img.ID = "img";
ListView3.Controls.Add(img);
ListView3.DataSource = ds; //DataSet containing column - colA with 20 rows
ListView3.DataBind();
I am basically trying to add control, which will be generated after some processing, to listview control; 我基本上是在尝试将控件添加到listview控件中,该控件将在经过一些处理后生成; but it keeps giving me error at
但它总是给我错误
ListView3.DataBind();
An exception of type 'System.InvalidOperationException' occurred in System.Web.Extensions.dll but was not handled in user code Additional information: An item placeholder must be specified on ListView 'ListView3'. Specify an item placeholder by setting a control's ID property to "itemPlaceholder". The item placeholder control must also specify runat="server".
And this is my ListView3 code: 这是我的ListView3代码:
<asp:ListView ID="ListView3" runat="server">
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server">
<tr id="itemPlaceholder" runat="server"></tr>
</table>
</LayoutTemplate>
<ItemTemplate>
</ItemTemplate>
</asp:ListView>
I have tried group template and placeholder control. 我尝试了组模板和占位符控件。 But I think I might have made a mistake in placeholder.
但是我认为我可能在占位符上犯了一个错误。 Please figure this error for me!
请为我找出这个错误! Thanks in advance.
提前致谢。
You could place the image directly inside the ItemTemplate
您可以将图像直接放在
ItemTemplate
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/img.png" AlternateText='<%# Eval("colA") %>' />
</ItemTemplate>
But to solve your error. 但是要解决你的错误。 A ListView repeats items, you when you want to add Controls to it you have to specify an index.
一个ListView重复项目,当您想要向其添加控件时,您必须指定一个索引。
ListView3.Items[i].Controls.Add(img);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.