[英]Dynamically create ImageButton and set its onclick function to ServerTransfer to another WebForm
因此,基本上,我會在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所述,您需要關聯click事件,而不僅僅是添加它。
您需要連接事件,而不是添加onclick屬性。 確實有兩種方法可以解決此問題(無需手動添加runat = server):
1。
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.Click += Unnamed1_Click;
photos.Controls.Add(imageButton);
}
2.第二種方法是在代碼中使用javascript ...而不是指定要調用的服務器端方法,只需使用:
imageButton.Attributes.Add("onclick", string.format("location.href('{0}');","whateverURL.html"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.