Reputation: 85
So basically im creating ImageButtons with a for loop inside a Div element,
But the onclick function i set when i create this ImageButtons is not working and it does not transfers.So i guess im not adding the function correctly although the button function below works fine
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();
}
Upvotes: 0
Views: 1744
Reputation: 253
Here's what i got:
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...
}
call LoadPictures() in your page load.
as elaw7 mentioned, you need to wire click event instead of just adding it.
Upvotes: 1
Reputation: 21
You need to wire up the event instead of adding the onclick attribute. There are two ways to go about this really (in neither one do you need to manually add 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. The second involves javascript... in your code instead of specifying the serverside method to call, simply use:
imageButton.Attributes.Add("onclick", string.format("location.href('{0}');","whateverURL.html"));
Upvotes: 0