我正在尝试根据按钮单击时c#函数返回的内容来填充一个带有行的html表。
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Populate" /></div><br>
<table id ="randtable" class="tablex">
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
</tr>
</table>
我的Button1_Click函数如下所示:
protected void Button1_Click(object sender, EventArgs e)
{
List<Entity> x = someFunction();
//I want to have each row in the table represent each entity. Assume each entity has 4 attributes which would go in Col1,Col2,Col3,Col4 in the table.
}
知道怎么做吗?我坚持使用html表而不是asp控件表的原因是保留html表的css,除非有一种方法可以使asp表看起来很吸引人。
答案 0 :(得分:2)
将您的表放在ListView控件中:
<asp:ListView runat=server id="lvResults">
<LayoutTemplate>
<table id ="randtable" class="tablex">
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
</tr>
<asp:PlaceHolder id="itemPlaceholder" runat="server"></asp:PlaceHolder>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><%# Eval(Container.DataItem, "col1") %></td>
<td><%# Eval(Container.DataItem, "col2") %></td>
<td><%# Eval(Container.DataItem, "col3") %></td>
</tr>
</ItemTemplate>
</asp:ListView>
然后在你的代码中加入以下内容:
protected void Button1_Click(object sender, EventArgs e)
{
List<Entity> x = someFunction();
lvResults.DataSource = x;
lvResults.DataBind()
}
答案 1 :(得分:0)
如果您特别想在html表上执行此操作,那么您可以在表的tbody元素上使用runat =“server”,然后在循环内填充表的行。
你的桌子是这样的:
<table id ="randtable" class="tablex"> <thead> <tr> <th>Col1</th> <th>Col2</th> </tr> </thead> <tbody id="mybody" runat="server"> //your dynamic rows from code behind </tbody> </table>
你的班级应该是这样的:
protected void Button1_Click(object sender, EventArgs e) { List<Entity> x = someFunction(); foreach (var entity in x) { mybody.InnerHtml += string.Format("<tr><td>{0}</td><td>{1}</td></tr>", entity.value1, entity.value2); } }