[英]Best way to handle table with dynamic columns
我通常在我的asp.net页面中处理Repeater
来生成表,但现在我需要在表中处理动态列 ,所以我想知道是否有一种通用的方法来使用Web控件来解决这个问题。
我从来没有使用过GridView
,所以我不知道用动态列渲染表是否更好? 你能建议我哪种方法比较合适吗? 有没有办法使用Repeater
实现这一目标?
您可以将AutoGenerateColumns设置为true的GridView
。 它将检查并添加DataSource
的列
<asp:sqldatasource id="CustomersSource"
selectcommand="SELECT CustomerID, CompanyName, FirstName, LastName FROM SalesLT.Customer"
connectionstring="<%$ ConnectionStrings:AWLTConnectionString %>"
runat="server"/>
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSource"
autogeneratecolumns="True"
emptydatatext="No data available."
allowpaging="True"
runat="server" DataKeyNames="CustomerID">
</asp:gridview>
知道如何处理这种情况非常重要。
情况1:您有一个现有的表,并且不时添加列(虽然这不是很实用),您可以立即转到GridView并将AutoGenerateColumns绑定属性设置为true。
情况2
您可以创建自己的HTmlHelper类来处理表。 为此您可以访问以下帖子:
如果你使用的是MVC。
如果你必须使用Repeater
这是一个快速的黑客攻击:
在.aspx中:
<asp:Repeater ID='rptr' runat='server'> <HeaderTemplate> <table> <thead> <tr> <th> Always visible header col </th> <th id='thHidable' runat='server' class='hideable'> Hideable header col </th> </tr> </thead> <tbody> </HeaderTemplate> <ItemTemplate> <tr> <td> Repeated col </td> <td id='tdHideable' runat='server' class='hideable'> Hideable repeated col </td> </tr> </ItemTemplate> <FooterTemplate> </tbody></table> </FooterTemplate> </asp:Repeater>
在后面的代码中(假设使用C#):
protected override void Page_Init()
{
this.rptr.ItemDataBound += new RepeaterItemEventHandler(rptr_ItemDataBound);
}
void rptr_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem item = (RepeaterItem)e.Item;
if (item.ItemType == ListItemType.Header)
{
HtmlTableCell thHidable = (HtmlTableCell)item.FindControl("thHidable");
if (hideCondition)
{
// thHidable.Visible = false; // do not render, not usable by client script (use this approach to prevent data from being sent to client)
thHidable.Style["display"] = "none"; // rendered hidden, can be dynamically shown/hidden by client script
}
}
else if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
HtmlTableCell tdHideable = (HtmlTableCell)item.FindControl("tdHideable");
if (hideCondition)
{
// tdHideable.Visible = false; // do not render, not usable by client script (use this approach to prevent data from being sent to client)
tdHideable.Style["display"] = "none"; // rendered hidden, can be dynamically shown/hidden by client script
}
}
}
(可选)如果要在客户端动态显示列(假设已呈现),请使用jQuery(为简洁起见):
$(".hideable").show();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.