使用ASP.NET GridView控件,在PageIndexChanged之后,如何在GridViewrow中禁用控件或单个单元格?
-
09-10-2019 - |
题
我有一个数据绑定的GridView控件,可以根据用户角色禁用单个单元格。这仅在第一页上起作用。
private void LimitAccessToGridFields()
{
if (User.IsInRole("Processing")) return;
foreach (GridViewRow gridViewRow in gvScrubbed.Rows)
{
var checkBox = ((CheckBox) gridViewRow.FindControl("cbScrubbed"));
checkBox.Enabled = false;
// ButtonField does not have an ID to FindControl with
// Must use hard-coded Cell index
gridViewRow.Cells[1].Enabled = false;
}
}
我在page_load上调用此方法,在哪里工作。我已经在PageIndexchaging和PageIndexchanged活动处理程序中尝试了它,但它不起作用。在调试时,它似乎已成功设置为在该行中的两个控件中启用false。我的目标是在更改页面后根据用户角色禁用这些字段。这应该如何完成?
解决方案 2
我发现这必须在RowDatabound事件处理程序中完成。
if (e.Row.RowType == DataControlRowType.DataRow)
{
// details elided ...
// Limits the access to grid fields.
if (!User.IsInRole("PROCESSING"))
{
cbstuff.Enabled = false; // a checkbox
e.Row.Cells[1].Enabled = false; //a link button
}
}
其他提示
您无需通过任何控件迭代以禁用或隐藏/可见。
渲染时,GridView控件中的每个单元格实际上都是HTML表参考(使用Firefly或Inspector查看页面中的代码)。
那么,为什么不迭代所有单元格以及每个单元格中发现的任何控件,都可以禁用它们呢?或者,您可以简单地循环浏览GridView的每一行,然后将其直接禁用或直接隐藏,这将影响行内的所有内容。
使用表单元格参考示例隐藏:
foreach (GridViewRow gRow in myGridView.Rows)
{
if (gRow.RowType == DataControlRowType.DataRow)
{
TableCellCollection tbcCol = (TableCellCollection)gRow.Cells;
foreach (TableCell tblCell in tbcCol)
tblCell.Enabled = false;
}
}
因此,这将通过表单元格禁用所有表单元。
或..为什么不只是禁用整个行?
foreach (GridViewRow gRow in myGridView.Rows)
{
if (gRow.RowType == DataControlRowType.DataRow)
gRow.Enable = false;
}
如果您需要固定或过滤特定的控制类型(复选框,文本框,标签等),并且仅影响这些控件,则只需对其进行测试!
foreach (GridViewRow gRow in myGridView.Rows)
{
if (gRow.RowType == DataControlRowType.DataRow)
{
TableCellCollection tbcCol = (TableCellCollection)gRow.Cells;
foreach (TableCell tblCell in tbcCol)
if (((TextBox)tblCell) != null)
((TextBox)tblCell).Enable = false;
}
}
不隶属于 StackOverflow