Skip to main content
 首页 » 编程设计

c#之asp.net gridview onrowcommand -->( GridViewCommandEventArgs)

2024年02月23日26kenshinobiy

请问如何获取gridview中按钮的文字或值? 但我想从此 onrowcommand 中获取文本值,它使用 GridViewCommandEventArgs 作为其参数。

好像我使用的 onrowdatabound 是 (GridViewRowEventArgs),这让我很容易在 gridview 中获取 button.text

string example = ((Button)e.Row.FindControl("btnStop")).Text; 

我想让 button.text 在 onrow 命令中执行 if else 循环。 谁知道怎么做?

 <asp:GridView ID="GridView1" runat="server" AllowPaging="True" CellPadding="2" CellSpacing="2"    HorizontalAlign="Center"   PageSize="5"  Width="133%" DataKeyNames="SurveyID" DataSourceID="SqlDataSource1"  
  AutoGenerateColumns="False" onrowcommand="stop_survey"  
       onrowdatabound="filter_select" onselectedindexchanging="selected"  
                                   > 

代码隐藏

 public void filter_select(object sender, GridViewRowEventArgs e) 
 { 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    {.... 
     ((Button)e.Row.FindControl("btnStop")).Text = "Start";  
    } 
 } 
 
 public void stop_survey(object sender, GridViewCommandEventArgs e) 
 { 
      //i want to get the "btnStop" button text which is nested on the gridview. 
 } 

我想获取 btnStop 文本,因为我想根据其文本使用不同的 sqlstatement(例如,开始或停止) 问题是我不能在 stop_survey 中执行 e.Row。 请指导我。

请您参考如下方法:

根据命令源行的引用创建 GridViewRow 的对象。

GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer; 

但请记住,在上面的代码中,您使用哪种类型的对象控件来调用事件是 LinkBut​​ton。但是,如果您从简单按钮调用 Rowcommand 事件,那么您需要这样写:

GridViewRow row = (GridViewRow)((Button)e.CommandSource).NamingContainer; 

创建行对象后,您可以使用 rowindex 从 Gridview 中简单地找到任何控件。

Label LabelEmail = (Label)GridView1.Rows[row.RowIndex].FindControl("LabelEmail"); 

您终于可以访问该控件的属性了。

LabelResult.Text = LabelEmail.Text;  

同上 你也可以使用GridViewRow rowindex找到gridview的Datakeys。

int code = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0].ToString());