2013-04-11 50 views
0

我試圖從GridView的頁腳點擊一個ImageButton事件點擊,但我沒有開火, 我會感謝任何幫助, 在此先感謝, 這裏是代碼添加單擊圖像buttonbutton裏面gridview動態

protected void grvBubDetails_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.Footer) 
    { 
     ImageButton imgbtnSendMail = new ImageButton(); 
     //ImageButton imgEdit = new ImageButton(); 
     imgbtnSendMail.ImageUrl = "~/Images/mail01.png"; 
     imgbtnSendMail.AlternateText = "Edit"; 
     imgbtnSendMail.ToolTip = "for send mail press here"; 
     imgbtnSendMail.Width = imgbtnSendMail.Height = 20; 
     //imgbtnSendMail.CommandName = "sendMail"; 
     //imgbtnSendMail.CommandArgument = "somevalue"; 
     imgbtnSendMail.Click += new ImageClickEventHandler(imgbtnSendMail_Click); 
     //imgbtnSendMail.Attributes["runat"] = "server"; 
     //imgbtnSendMail.Attributes["onclick"] = "imgbtnSendMail_Click"; 
     e.Row.Cells[6].Controls.Add(imgbtnSendMail); 
    } 
} 
protected void imgbtnSendMail_Click(object sender, ImageClickEventArgs e) 
{ 
     string Text = "Image clicked"; 
} 

回答

2

更新grvBubDetails_RowDataBound事件這樣的;

ImageButton imgbtnSendMail = new ImageButton(); 
imgbtnSendMail.CommadName = "cmdSendMail"; // add this line 
imgbtnSendMail.CommadArgument = "also you can pass a parameter from here"; 

將RowCommand事件添加到網格視圖。在RowCommand事件處理函數中執行此操作;

if(e.CommandName.equals("cmdSendMail")){ 
    string Text = "Image clicked"; 
    string argument = e.CommandArgument; 
} 

更新:

網格視圖的pageLoad的事件之後解僱RowCommand事件。您的按鈕在每次重新加載頁面後都會被刪除,並且沒有重新創建,因爲rowDatabound事件不會觸發。

工作代碼:

public partial class _Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
      List<string> list = new List<string>() 
      { 
       "item 1", 
       "item 2", 
       "item 3" 
      }; 
      GridView1.DataSource = list; 
      GridView1.DataBind(); 
     } 

     // make sure outside of !IsPostback 
     // recreate button every page load 
     Button btn = new Button(); 
     btn.CommandName = "cmdSendMail"; 
     btn.CommandArgument = "sample arg"; 
     btn.Text = "send mail"; 
     GridView1.FooterRow.Cells[0].Controls.Add(btn); 
    } 

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) 
    { 
     Response.Write(e.CommandName + new Random().Next().ToString()); 
    } 
} 
+0

我也試過,但它不進去grvBubDetails_RowCommand!這是因爲它是一個頁腳? – 2013-04-11 09:54:51

+0

我做了類似的代碼之前用Button,但用ImageButton我不知道爲什麼它不起作用 – 2013-04-11 09:57:35

+0

EnableViewState是否爲頁面和網格視圖控件?如果在頁面加載事件中有數據代碼,請確保它位於if(!IsPostBack)塊中。 – 2013-04-11 10:06:24

0

您必須聲明對全球範圍內ImageButton(職業等級)

ImageButton imgbtnSendMail = new ImageButton(); 
protected void grvBubDetails_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.Footer) 
    { 
+0

感謝烏拉圭回合的答覆,我試過,但它不工作 – 2013-04-11 09:55:29