在gridview中动态添加click to imagebutton

时间:2013-04-11 09:38:17

标签: c# asp.net web-applications imagebutton

我试图从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";
}

2 个答案:

答案 0 :(得分: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());
    }
}

答案 1 :(得分:0)

您必须在全局范围(类级别)

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