如何在asp:Table中隐藏列? [英] How do I hide a column in an asp:Table?
问题描述
我有一个简单的ASP.NET表,如下所示:
I have a simple ASP.NET table like so:
<asp:Table id="tbl">
<asp:TableHeaderRow id="header">
<asp:TableHeaderCell id="hcell1" />
</asp:TableHeaderRow>
<asp:TableRow id="row">
<asp:TableCell id="cell1" />
</asp:TableRow>
</asp:Table>
ID由组成,实际表中还有更多列.我希望能够以编程方式从背后的代码中隐藏任何列(不是javascript).这可能吗?此时,我可以轻松地将标记更改为几乎任何所需的标记,因此我可以提出建议.
The ID's are made up and the actual table has several more columns. I want to be able to hide any column programmatically from the codebehind (not javascript). Is this possible? At this point I can easily change the markup to be pretty much whatever I want, so I'm open to suggestions.
很抱歉,请清除.我希望能够以这样一种方式简单地隐藏一列:如果我添加了新行,则不需要更改任何用于处理隐藏的代码.理想的情况是:
Sorry to be clear. I want to be able to simply hide a column in such a way that if I add a new row I don't want to have to change any of the code that handles the hiding. The ideal would be something like:
tbl.Columns["ColName"].Visible = false;
不太理想的情况是for/foreach循环执行类似的操作.
Less ideal would be a for/foreach loop that did something similar.
推荐答案
尝试使用此扩展方法,它将扩展Table类,并添加方法以按索引和TableHeaderCell的ID隐藏列(如果存在):
Try using this extension method, it extends the Table class, adding methods to hide columns by index and by the ID of a TableHeaderCell (if one exists):
但是请注意,它不提供任何逻辑来满足跨其他列的情况列:
Note however, that it does not provide any logic to cater for columns which span other columns:
示例
tbl.HideColumn("HeaderID");
tbl.HideColumn(0);
课程
public static class TableExtensions
{
public static void HideColumn(this Table table, int index)
{
foreach (TableRow row in table.Rows)
{
if (row.Cells.Count-1 >= index)
{
row.Cells[index].Visible = false;
}
}
}
public static void HideColumn(this Table table, string id)
{
int index = 0;
bool columnFound = false;
if (table.Rows.Count > 1)
{
TableHeaderRow headerRow = table.Rows[0] as TableHeaderRow;
if (headerRow != null)
{
foreach (TableHeaderCell cell in headerRow.Cells)
{
if (cell.ID.ToLower() == id.ToLower())
{
columnFound = true;
break;
}
index++;
}
}
}
if(columnFound)
HideColumn(table, index);
}
}
这篇关于如何在asp:Table中隐藏列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!