动态添加click到gridview中的imagebutton
本文关键字:中的 imagebutton gridview 添加 click 动态 | 更新日期: 2023-09-27 18:08:50
我试图从gridview的页脚触发ImageButton的事件点击,但我没有触发,我会很感激你的帮助。提前感谢,下面是代码
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";
}
像这样更新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());
}
}
必须在全局作用域(类级别)上声明ImageButton
ImageButton imgbtnSendMail = new ImageButton();
protected void grvBubDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{