How to find label control in the RowCommand method of grid view?

夙愿已清 提交于 2019-12-14 04:00:04

问题


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

Compiler throwing error as

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


回答1:


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

Because sender here is Gridview and not linkbutton.

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>

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;
   }
}


来源:https://stackoverflow.com/questions/33968738/how-to-find-label-control-in-the-rowcommand-method-of-grid-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!