【问题标题】:Command behind a GridView ButtonFieldGridView ButtonField 后面的命令
【发布时间】:2011-05-11 11:54:45
【问题描述】:

我有一个关于 GridView 中 ButtonField(图像类型)背后的命令的问题。

有一个名为 gvIngevuld 的 GridView,我在其中显示数据行和 1 个 ButtonField 行。 现在我必须将代码放在这些按钮后面(每个按钮都相同),以将一些东西放在 PDF 格式中。 问题是我不知道如何将代码放在这些按钮后面? 我的代码:

<asp:ButtonField ButtonType="Image" ImageUrl="~/Images/pdf.png"  CommandName="pdf_click" />

如您所见,我使用了 CommandName="pdf_click" 属性,但是当我单击其中一个按钮时,只有回发,但没有任何反应。 有谁能帮帮我吗?

如果需要,后面的代码:

protected void pdf_click(object sender, EventArgs e)
{
    lblWelkom.Text = "Succes!";
}

谢谢。

【问题讨论】:

  • 尝试将 CommandName 更改为 onclick,看看是否可以解决问题。此外,可能需要添加 runat="server" 到它。我知道我们做了一个隐藏按钮,但这只是我们连接它的特定方式。

标签: c# .net asp.net gridview buttonfield


【解决方案1】:

您应该使用 gridview 的RowCommand 事件。将 commandArgument 设置为项目的唯一键。 (默认情况下,它通过行的索引)

void gvIngevuld_RowCommand(Object sender, GridViewCommandEventArgs e)
 {
 // If multiple buttons are used in a GridView control, use the
 // CommandName property to determine which button was clicked.
 if(e.CommandName=="pdf_click")
  {
   // Convert the row index stored in the CommandArgument
   // property to an Integer.
   int index = Convert.ToInt32(e.CommandArgument);

   // Retrieve the row that contains the button clicked 
   // by the user from the Rows collection.
   GridViewRow row = gvIngevuld.Rows[index]; 
   //gbIngevuld is your GridView's name

   // Now you have access to the gridviewrow.
  }  
}   

另外,如果你设置了gridview的DataKeyNames,你可以通过如下方式访问:

    int index = Convert.ToInt32(e.CommandArgument);
    int ServerID = Convert.ToInt32(GridView1.DataKeys[index].Value);

【讨论】:

    【解决方案2】:

    只是一个补充,我编写并尝试了完全相同但按钮仍然无法正常工作......

    ...过了一段时间我才意识到我忘记了一件事,那就是 OnRowCommand="&lt;YourGridViewName&gt;_RowCommand" 在 **.cs* 文件中的 GridView 元素中

    【讨论】:

      【解决方案3】:

      CommandName 属性未定义要调用的方法。为此,您需要创建一个绑定到控件命令事件的方法。
      恐怕我对 GridViews 不太了解,但我认为最简单的方法是在 Visual Studio 的设计视图中选择它,转到属性,单击事件按钮(看起来像闪电flash) 并双击 RowCommand 事件属性。这应该会自动创建一个绑定到命令按钮事件的方法。
      然后,您可以使用 GridViewCommandEventArgs 参数访问 CommandName、CommandArgument 和 CommandSource 属性,以确定是哪个按钮触发了事件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-13
        • 1970-01-01
        • 2011-02-25
        • 1970-01-01
        • 1970-01-01
        • 2015-07-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多