问题描述
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lblUser = clickedRow.FindControl("lblFullName") as Label;
Label lblUserId = (Label)clickedRow.FindControl("lblUserId");
编译器抛出错误
推荐答案
当前代码的问题是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中可能有多个控件,这些控件可以引发此事件(或者您将来可以添加它们),因此可以在LinkButton中添加一个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
引发,然后安全地使用将为LinkButton
的e.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方法中找到标签控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!