0

我将一些图像按钮放入我的网格视图中,但我无法捕获点击事件。在 gridview 中创建单击事件或创建 OnRowCommand 处理程序均无效。

单击按钮只是回发到当前页面。

我像这样添加我的按钮:

protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string status = DataBinder.Eval(e.Row.DataItem, "visitstatusuid").ToString();

        string visitUID = DataBinder.Eval(e.Row.DataItem, "visituid").ToString();

        Color backColor = Color.White;
        Color foreColor = Color.Black;

        ImageButton b;

        switch (status)
        {
            case "U": // Unallocated
                backColor = ColorTranslator.FromHtml("#B2A1C7");
                b = new ImageButton();
                b.Width = Unit.Pixel(25);
                b.Height = Unit.Pixel(30);
                b.AlternateText = "Book";
                b.ImageUrl = "../../Images/New/booking.gif";
                b.ToolTip = "Booking";
                b.CommandName = "Booking";
                b.CommandArgument = visitUID;
                b.CausesValidation = false;

                e.Row.Cells[(e.Row.Cells.Count - 3)].Controls.Add(b);

等等

4

5 回答 5

0

除非您在其他地方添加事件处理程序,否则您需要AutoEventWireup="true"在您的 aspx 文件的页面指令中进行设置。

话虽如此,我更喜欢显式连接事件,而不是使用AutoEventWireup将此行添加到您的OnInit方法中:

gridview1.RowDataBound += this.gridview1_RowDataBound;
于 2009-09-28T12:36:42.377 回答
0

创建按钮时,您需要附加处理程序:

b.Click += MyButtonClickEventHandler;

编辑
不要在 OnRowDataBound 处理程序中创建按钮,而是使用 OnRowCreated。
这可确保在回发时重新创建按钮。

例子:

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack) {
    BindData();
  }
}

protected void BindData()
{
  // Do your databinding here.
}

protected void MyGridView_RowCreated(object sender, GridViewRowEventArgs e)
{
  var b = new ImageButton();
  b.AlternateText = "Click Me!";
  // Etc.

  b.Click += MyButton_Click;
  // Add the button to the column you want.
}

protected void MyButton_Click(object sender, ImageClickEventArgs e)
{
  // Do your thing...
}
于 2009-09-28T12:38:11.613 回答
0

对于使用 RowDataBound 的方法,您需要在每次页面加载时重新绑定网格,并确保不晚于生命周期中的 OnLoad 执行此操作,以便及时注册点击事件。

我成功的另一种方法是创建一种新方法来设置 DataGrid 按钮,例如

void PerformConditionalGridFormatting()
{
    foreach (GridViewRow row in gvCaseList.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
             ... Add your buttons to the cells here
        }
    }
}

然后在每次执行手动数据绑定时调用该方法,并且在每次回发时调用该方法,即在 OnLoad 处理程序中执行以下操作:

if (Page.IsPostBack) PerformConditionalGridFormatting();

这种方法的优点是您不必在每次回发时都进行数据绑定,从而节省了资源。

于 2009-09-28T13:31:24.510 回答
0

为 gridview 创建一个 RowCommand 事件处理程序并检查命令名称以查看它是否是您的按钮触发它

大意的东西

void gridview1_RowCommand(object sender, args e)
{

if (e.CommandName == "Booking")
{
// call your desired method here
}

}
于 2009-09-28T14:00:48.543 回答
0

将网格的绑定事件放入不回发。

于 2009-10-08T06:33:39.230 回答