簡體   English   中英

使用ASP.NET GridView控件,如何在PageIndexChanged之后禁用GridViewRow中的控件或單個單元格?

[英]With the ASP.NET GridView control, how can I disable controls or individual cells in a GridViewRow after PageIndexChanged?

我有一個數據綁定的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事件處理程序中對其進行了嘗試,但該方法無效。 調試時,似乎已成功將行中的兩個控件的Enabled設置為false。 我的目標是在更改頁面后根據用戶角色禁用這些字段。 應該如何完成?

您不需要遍歷任何控件來禁用或隱藏/可見它們。

呈現時,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;
                }
            }

因此,將逐個表格單元禁用所有表格單元。

OR ..為什么不禁用整個行呢?

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;
  }
}

我發現這必須在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
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM