2009-09-28 109 views
0

我在GridView中放置了一些圖像按鈕,但無法捕獲單擊事件。既不創建一個點擊事件,也不在GridView中創建一個OnRowCommand處理程序。似乎無法在asp.net中的gridview中捕獲按鈕點擊

單擊按鈕只需回發到當前頁面。

添加我的按鈕,像這樣:

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); 

回答

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

確實,我試過b.Click + =新的ImageClickEventHandler(gridviewButtonClick);並突出顯示它,但斷點沒有命中當我點擊按鈕時 – NibblyPig 2009-09-28 12:43:29

+0

當點擊按鈕回發發生 您是否在回發時重新創建按鈕? – 2009-09-28 12:58:10

0

除非您要添加的事件處理程序的其他地方,你需要設置AutoEventWireup="true"在你的aspx文件的頁指令。

話雖這麼說,我更喜歡明確的佈線事件等等,而不是使用AutoEventWireup此行添加到您的OnInit方法:

gridview1.RowDataBound += this.gridview1_RowDataBound; 
+0

它已被設置爲true :( – NibblyPig 2009-09-28 12:37:32

+0

恐怕這不起作用:( – NibblyPig 2009-09-28 12:46:56

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(); 

這種方法的好處是,你不必須在每次回發時都進行數據綁定,從而節省資源。

0

創建爲GridView一個RowCommand事件處理程序,並檢查命令名,看它是否是你的按鈕觸發它

東西的

void gridview1_RowCommand(object sender, args e) 
{ 

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

} 
0

效果將電網的結合事件不發回。