如何在网格视图的RowCommand方法中找到标签控件? [英] How to find label control in the RowCommand method of grid view?

查看:72
本文介绍了如何在网格视图的RowCommand方法中找到标签控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lblUser = clickedRow.FindControl("lblFullName") as Label;
Label lblUserId = (Label)clickedRow.FindControl("lblUserId");

编译器抛出错误

无法投射类型为'System.Web.UI.WebControls.GridView'的对象

Unable to cast object of type 'System.Web.UI.WebControls.GridView'

推荐答案

当前代码的问题是GridView的RowCommand事件是由gridview本身而不是由单个控件引发的,因此您的转换将失败:-

The problem with your current code is that the GridView's RowCommand event is raised by gridview itself and not by an individual control thus your cast will fail:-

(LinkButton)sender

因为这里的发件人是Gridview,而不是linkbutton.

Because sender here is Gridview and not linkbutton.

现在,您的gridview中可能有多个控件,这些控件可以引发此事件(或者您将来可以添加它们),因此可以在LinkBut​​ton中添加一个CommandName属性,如下所示:-

Now, you may have multiple controls in your gridview which can raise this event(or you may add them in future) so add a CommandName attribute to your LinkButton like this:-

<asp:LinkButton ID="myLinkButton" runat="server" Text="Status" 
     CommandName="myLinkButton"></asp:LinkButton>

最后,在RowCommand事件中,您可以先检查事件是否由LinkButton引发,然后安全地使用将为LinkButtone.CommandSource属性,然后从中找到Gridview的包含行.

Finally in the RowCommand event you can first check if the event is raised by the LinkButton and then safely use the e.CommandSource property which will be a LinkButton and from there find the containing row of Gridview.

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
   if (e.CommandName == "myLinkButton")
   {
      LinkButton lnk = (e.CommandSource) as LinkButton;
      GridViewRow clickedRow = lnk.NamingContainer as GridViewRow;
   }
}

这篇关于如何在网格视图的RowCommand方法中找到标签控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆