我通常會處理Repeater
以在我的asp.net頁面中生成表,但現在我需要在我的表中處理動態列,所以我想知道是否有一種常見的方法來處理使用網頁控制解決這個問題。動態列處理表的最佳方式
我從來沒有用過GridView
,所以我不知道這是否是更好地渲染動態列的表?你能建議我這是更合適的方法嗎?有沒有辦法使用Repeater
來實現這個目標?
我通常會處理Repeater
以在我的asp.net頁面中生成表,但現在我需要在我的表中處理動態列,所以我想知道是否有一種常見的方法來處理使用網頁控制解決這個問題。動態列處理表的最佳方式
我從來沒有用過GridView
,所以我不知道這是否是更好地渲染動態列的表?你能建議我這是更合適的方法嗎?有沒有辦法使用Repeater
來實現這個目標?
,你可以一個GridView
與AutoGenerateColumns設置爲true。它會檢查並添加列在您的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
How to create MVC HtmlHelper table from list of objects
: 爲此,您可以訪問下面的文章。
OP提及'Repeater',這是一個衆所周知的ASP.NET WebForms控件。 –
這裏有一個快速的黑客要做到這一點,如果你必須使用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();
爲什麼我討厭的SqlDataSource這麼多? – Jonathan