繁体   English   中英

似乎无法捕获asp.net的gridview中的按钮单击

[英]Can't seem to capture a button click in a gridview in asp.net

我在网格视图中放置了一些“图像按钮”,但无法捕获单击事件。 在gridview中创建click事件或创建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);

等等

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

话虽这么说,我更喜欢显式地连接事件,所以不要使用AutoEventWireup将此行添加到您的OnInit方法中:

gridview1.RowDataBound += this.gridview1_RowDataBound;

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

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

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

我成功的另一种方法是创建一种新的方法来进行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();

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

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

有影响的东西

void gridview1_RowCommand(object sender, args e)
{

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

}

放置网格的绑定事件不要回发。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM