maryam mohammadi
maryam mohammadi

Reputation: 694

how to load image in ImageButton in codebehind?

i want to create my imagebutton in code behind. so i use this code:

 LiteralControl ltr = new LiteralControl();

 ltr.Text = "<asp:ImageButton class=\"stylImage\" AlternateText=\"Signature\" runat=\"server\" ImageUrl=\"~/images/Workflow/digital-signature-pic.jpg\" OnCommand=\"Image_OnCommand\" CommandName=\"imgclick\"/>";

but it doesn't work. nothing display.

Any Idea?!

Upvotes: 2

Views: 6527

Answers (3)

chridam
chridam

Reputation: 103375

Instead of using a Literal control, add a panel control and include the ImageButton control in your panel. You should add the controls in the Page Init event

protected void Page_Init(object sender, EventArgs e)
{
    ImageButton imgBtn = new ImageButton();
    imgBtn.ID = "img_id";
    imgBtn.ImageUrl = "~/images/Workflow/digital-signature-pic.jpg";
    imgBtn.AlternateText= "Signature";
    imgBtn.Click += (source, args) =>
    {
        // do something
    };
    Panel1.Controls.Add(imgBtn);
}

Upvotes: 3

Bex
Bex

Reputation: 4918

You can't write a server side control to a literal. You have two options,

  • either set the image button directly on the page and change the visibility attribute
  • Or Add a placeholder or panel control and dynamically add the image button to it, something like this

            ImageButton btn = new ImageButton(); 
            btn.ImageUrl = "my image url";
    
            btn.Click += btn_Click;
    
            btn.ID = "create an ID";
            etc....
            ph.Controls.Add(btn);
    

Upvotes: 0

Justin Harvey
Justin Harvey

Reputation: 14672

You need to add it to a container on the page, see this article:

http://msdn.microsoft.com/en-us/library/kyt0fzt1.aspx

Upvotes: 0

Related Questions