GridView ButtonField后面的命令

时间:2011-05-11 11:54:45

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

我对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!";
}

感谢。

3 个答案:

答案 0 :(得分:28)

您应该使用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);

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

...我花了一些时间才意识到我忘记了一件事 OnRowCommand="<YourGridViewName>_RowCommand" 在** .cs *文件

中的GridView元素内