0

I am writing project in asp.net C#. I want to create Image programmatically by the following code:

protected void Page_Load(object sender, EventArgs e)
        {
            Image image = new Image();
            image.ID = "image11";
            image.ImageUrl = "a.jpg";
            image.ImageAlign = ImageAlign.AbsMiddle;
            image.Visible = true;

        }

But nothing is displayed when I run the project. How to create image from file and display it in the page by writing code in .cs file?

3 Answers 3

1

You have created an image control but you have not added it to your form. Write the below code to add the image control to your form.

form1.Controls.Add(image);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks!It works. But my aim was to build an image gallery. If I add second image to the panel I lose the previous image. So how to add multiple images to the panel?
@NurlanKenzhebekov if you want to add multiple images then you should use a datalist and a panel, in datalist a small image appears like an icon but when a person selects that icon display that image in a panel .
1

At this point, you have just created an image, but you haven't added it to a control or page context to be displayed. You essentially said

int x = 10;

but then never did anything with x.

ASP.NET uses composition, so it maintains a collection of controls, with each control also containing a collection of children nodes. You need to add the image to a container. For instance, if you want to add the image to a panel named myPanel, it would be

myPanel.Controls.Add(image);

Check out this article.

2 Comments

Thanks!It works. But my aim was to build an image gallery. If I add second image to the panel I lose the previous image. So how to add multiple images to the panel?
Make sure you do: image = new Image() for each image. If you don't you are just change the original image's attributes. If that is not it, please post code with an edit.
0

You will need to create panel and then you will have to add that image to panel.

Panel Panel1= new Panel();
form1.Controls.Add(image);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.