【问题标题】:Enable hyperlink field in gridview while all other controls are disabled在所有其他控件被禁用时,在 gridview 中启用超链接字段
【发布时间】:2011-09-28 16:37:53
【问题描述】:

出于商业目的,我必须禁用我的 gridview 上的所有控件。 Me.gvLineItems.Enabled=False

但是,我需要启用一个超链接字段,所以我尝试了这个:

                For Each Row As GridViewRow In Me.gvLineItems.Rows
                    Dim hrf As HyperLink
                    hrf = CType(Row.Cells(16).Controls(0), HyperLink)
                    hrf.Enabled = True
                Next

我调试代码并将超链接字段设置为 true,但是当我运行应用程序时,该字段仍然被禁用...

但如果我去掉 Me.gvLineItems.Enabled=False,只需将其注释掉并更改我的代码以禁用超链接字段:

                For Each Row As GridViewRow In Me.gvLineItems.Rows
                    Dim hrf As HyperLink
                    hrf = CType(Row.Cells(16).Controls(0), HyperLink)
                    hrf.Enabled = False
                Next

这很好用...

但这不是我需要的 :(,只是试图重新启用链接字段...

编辑

我也在 rowdatabound 事件中尝试过这个:

If Me.gvLineItems.Enabled = False Then
                For i As Integer = 0 To e.Row.Cells.Count - 1
                    If TypeOf (e.Row.Cells(i).Controls(0)) Is HyperLink Then
                        Dim h As HyperLink = CType(e.Row.Cells(i).Controls(0), HyperLink)
                        h.Enabled = True
                        Exit For
                    End If
                Next
            End If

【问题讨论】:

    标签: asp.net vb.net


    【解决方案1】:

    我明白了:

    For i As Integer = 0 To e.Row.Cells.Count - 1
                    If TypeOf (e.Row.Cells(i).Controls(0)) Is HyperLink Then
                        Dim h As HyperLink = CType(e.Row.Cells(i).Controls(0), HyperLink)
                        h.Enabled = True
                        Exit For
                    Else
                        e.Row.Cells(i).Enabled = False
                    End If
                Next
    

    【讨论】:

    • 非常很容易破解。一旦你得到它的工作,我的答案会更好。
    【解决方案2】:

    您需要使用某种类型的递归逻辑来循环遍历所有单元格并禁用控件,条件是排除超链接控件。通过在行级别禁用控件,父容器(即 GridViewRow)的启用状态将始终覆盖控件的启用状态。

    我会在RowDataBound 事件中添加一些递归逻辑。试试这样的:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DisableControls(e.Row);
    }
    
    private void DisableControls(WebControl parentCtrl)
    {
        if (parentCtrl.HasControls())
        {
            foreach (WebControl ctrl in parentCtrl.Controls)
            {
                ctrl.Enabled = ctrl is HyperLink;
                DisableControls(ctrl);
            }
        }
        else
        {
            parentCtrl.Enabled = parentCtrl is HyperLink;
        }        
    }
    

    【讨论】:

    • 这不起作用,因为启用仍然不是Control 类型的属性。请阅读 MSDN。
    • 请再次阅读我的答案的顶部。您不能禁用整行。您必须遍历单元格并单独禁用控件。如果禁用整行,则该行将优先于该行中任何控件的启用状态。
    • 我想我已经在DisableControls 方法中将Control 的所有实例替换为WebControl,但是如果我遗漏了什么,请将其更改为WebControl
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    相关资源
    最近更新 更多