c# - 动态创建ImageButton并将其onclick函数设置为ServerTransfer到另一个WebForm

标签 c# javascript asp.net webforms

所以基本上我在 Div 元素内使用 for 循环创建 ImageButtons,
但是我在创建此 ImageButtons 时设置的 onclick 函数不起作用,并且无法传输。所以我猜我没有正确添加该函数,尽管下面的按钮函数工作正常

 protected void Page_Load(object sender, EventArgs e)
        {
              foreach (string strFileName in Directory.GetFiles(Server.MapPath("~/path/")))
            {
                  ImageButton imageButton = new ImageButton();
                  FileInfo fileInfo = new FileInfo(strFileName);
                  imageButton.ImageUrl = "~/path/" + fileInfo.Name.ToString();
                  imageButton.Attributes.Add("ID" , strFileName);                                  
                  imageButton.Attributes.Add("class","imgOne");
                  imageButton.Attributes.Add("runat", "server");
                  imageButton.Attributes.Add("OnClick", "toImageDisplay");
                  photos.Controls.Add(imageButton);



            }



        }
        public void toImageDisplay() 
        {
            Server.Transfer("ImageDisplay.aspx");
        }

        protected void Unnamed1_Click(object sender, EventArgs e)
        {
            toImageDisplay();
        }

最佳答案

这是我得到的:

    private void LoadPictures()
    {
        foreach (string strFileName in Directory.GetFiles(Server.MapPath("~/path/")))
        {
            ImageButton imageButton = new ImageButton();
            FileInfo fileInfo = new FileInfo(strFileName);
            imageButton.ImageUrl = "~/path/" + fileInfo.Name.ToString();
            imageButton.Click += new ImageClickEventHandler(imageButton_Click);
            imageButton.ID = Path.GetFileName(strFileName);
            photos.Controls.Add(imageButton);
            //imageButton.Attributes.Add("ID", strFileName);
            //imageButton.Attributes.Add("class", "imgOne");
            //imageButton.Attributes.Add("runat", "server");
            //imageButton.Attributes.Add("OnClick", "toImageDisplay");
        }
    }

    void imageButton_Click(object sender, ImageClickEventArgs e)
    {
        //your code...
    }

在页面加载时调用 LoadPictures()。

正如 elaw7 提到的,您需要连接点击事件,而不仅仅是添加它。

关于c# - 动态创建ImageButton并将其onclick函数设置为ServerTransfer到另一个WebForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24938921/

相关文章:

c# - 是否可以通过 Word API 查看单词的不同形式?

c# - Nancy 查看内部服务器错误

c# - 带有表达式参数的过程

ASP.NET MVC2 : How to render a view if has multiple different models

c# - 未知加密类型打开 pdf 文件

javascript - 嵌套 async/await 是反模式吗?

javascript - 一张 Canvas 用于交互,三张 Canvas 用于显示

javascript - js react native : How to animate a view's position with translateX?

C# ASP :ListBox hide vertical scrollbar

asp.net - 设置 SelectedRowStyle 属性来更改所选行的背景颜色是个坏主意吗?