【问题标题】:Changing the text of a linkbutton of a gridview dynamically on the basis of a column value根据列值动态更改gridview的链接按钮的文本
【发布时间】:2014-06-26 11:30:45
【问题描述】:

我来自 PHP 背景。我有从数据库中填充的 GridView 的以下代码。我想根据网格中状态列的值更改链接按钮的文本。例如,如果状态列的值为“待定”,则链接按钮应显示文本 Edit Details 而不是 View Details。我该怎么做?

<asp:GridView ID="empres1" 
    runat="server" 
    AllowPaging="True" 
    AutoGenerateColumns="False" 
    onrowcommand="empres1_RowCommand" 
    onrowediting="empres1_RowEditing" 
    onselectedindexchanged="empres1_SelectedIndexChanged1">

        <asp:BoundField DataField="Status" HeaderText="Status" />
        <asp:BoundField DataField="comments" HeaderText="comments"   />
        <asp:TemplateField HeaderText="" SortExpression="">  
            <ItemTemplate>   
                <asp:LinkButton ID="LinkButtonEdit" runat="server" 
                    CommandName="ShowPopup" 
                    CommandArgument='<%#Eval("EmployeeId") %>'>View Details
                </asp:LinkButton> 
                                                 -------------------^
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    您需要使用 RowDataBound 事件来动态设置文本。获取对链接按钮的引用并根据数据项设置它的文本。所以你的代码应该是这样的。

        protected void empres1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton button =
            e.Row.Cells[2].FindControl("LinkButtonEdit");
            if (button != null)
            {
                DataRow dr = e.Row.DataItem;
                if (dr["status"].ToString() == "Pending")
                {
                    button.Text = "Edit Details";
                }
                else
                {
                    button.Text = "View Details";
                }
            }
    
        }
    }
    

    代码在语法上可能并不完美,但你会从中得到一个想法。

    【讨论】:

      【解决方案2】:

      您可以使用网格视图的服务器端事件:

      在这种情况下,您可以访问在该行中创建的控件,并对其进行修改,如下所示:

      if(e.Row.RowType == DataControlRowType.DataRow)  // (1)
      {
        // modify the row here
      }
      

      (1) 这会跳过页眉和页脚,因此代码只针对“常规”行运行

      // modify the row here 中,您可以访问行内的控件,并对其进行修改。

      您也可以使用GridView.RowDataBound Event,它具有传递给行的数据信息(与上一个示例类似)。

      在这两种情况下,您都可以使用Row,也可以使用access all of its properties。您可能会使用这些属性:

      • Cells:行的单元格(列)
      • Controls:行内控件
      • DataItem:它允许您访问绑定到此路由的数据(您可以使用调试器查看它如何进行必要的转换)

      该过程是查看DataItem 中的数据,并查找您需要修改的控件(或单元格)。 (我坚持在调试器上使用断点来浏览属性的值……有点麻烦,尤其是数据项)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-08
        • 1970-01-01
        • 2011-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多