簡體   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