【问题标题】:Conditional hyperlinkfield in a gridview? ASP.net网格视图中的条件超链接字段? ASP.net
【发布时间】:2009-11-13 11:59:20
【问题描述】:

我将一个超链接字段放入一个网格视图中,但我意识到有时我希望它可以点击,有时却不能,具体取决于数据。

如果项目是 A 或 B,我想要一个指向 bibble.aspx?id=123 的超链接,否则我只想要纯文本。

最好的方法是什么?我应该为此使用其他类型的字段吗?

【问题讨论】:

    标签: asp.net gridview


    【解决方案1】:
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
         onrowdatabound="GridView1_RowDataBound">
        <Columns>
            <asp:TemplateField HeaderText="Column to check">
                <ItemTemplate>
                    <asp:Label runat="server" ID="lblCrtl" Text='<%# Eval("Name") %>' />
                </ItemTemplate>
            </asp:TemplateField>
    
            <asp:TemplateField HeaderText="Column Name">
    
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    
    
    
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // you may need to do this if you didnt use templatefield;
            // string val = e.Row.Cells[<column index>].Text;
            // if its templatefield do following;
            Label lbl = e.Row.FindControl("lblCrtl") as Label; 
    
            Button btn = null;
    
            if (lbl.Text == "Car") // put your own value to check, my case it was Car
            {
                btn = new Button();
                btn.Text = "Test";
                e.Row.Cells[1].Controls.Add(btn); // cells<column index that control will be added>
            }
        }
    }
    

    【讨论】:

    • 我尝试了类似的方法,使用模板字段,但由于某种原因 e.Row.Cells[7].Text 是“”,这不可能是正确的......
    • 如果您使用了模板字段,则无法访问像 e.Row.Cells[7].Text 这样的控件,您宁愿使用 e.Row.FindControls("ctrlID");并根据您使用的控件使用其属性。
    • 谢谢,问题是我想要标签或超链接。那么我应该将标签放入模板字段,然后在代码隐藏中,将其删除并添加超链接吗?也不会给它一个 ID 导致页面上有多个具有相同 ID 的标签?
    • 控件在哪里,可以帮助您确定是标签还是超链接?
    • 实际上是返回该字段的数据。这是一个东西的状态,如果状态设置为“无”,它应该是一个超链接,否则它只是纯文本。
    【解决方案2】:

    使用模板字段和超链接控件可能会更好,NavigateUrl 由三元运算符确定。

    【讨论】:

      【解决方案3】:

      您需要处理 GridView 的 RowDataBound 事件。

      link 演示了如何使用 RowDataBound 事件在数据源中的字段值显示在 GridView 控件中之前对其进行修改。

      【讨论】:

      • 是的,我刚刚完成了这项工作,并且即将添加一个超链接......现在我刚刚遇到的唯一问题是如何让 ID 附加到超链接 url。它不显示为字段(尽管它构成了另一个字段中超链接的一部分),尽管它被拉回数据源中。如何在代码中提取它?通常我只会使用 datakeyname 属性。这可能很明显,我对 gridviews 还是新手;D
      • 我去吃午饭了 - 看起来你同时得到了解决方案 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      • 1970-01-01
      • 2023-04-06
      相关资源
      最近更新 更多