- This topic helps to add picturebox control dynamically to the form using C#
- When we click the Button Control, a picturebox with picture added to the form dynamically, picture also added dynamically to the form through setting its background image through coding.
- Tools needed: Button1 (Button1).
PictureBox Control – Add PictureBox control dynamically to the form using C#
- PictureBox control represents a Windows picture box control for displaying an image.
- Syntax for picturebox control
|
1 2 3 4 5 |
[DockingAttribute(DockingBehavior.Ask)] [ComVisibleAttribute(true)] [ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)] [DefaultBindingPropertyAttribute("Image")] public class PictureBox : Control, ISupportInitialize |
Code to display an Image -Â Add PictureBox control dynamically to the form using C#
|
1 |
PictureBox1.Image = Image.FromFile(strFileName); |
- Through the above code we are loading image to the Image Property of the PictureBox Control.
|
1 |
this.Controls.Add(m_pictureBox(i)); |
- Above code adds picturebox control to the form of our application, you can add any controls to your application through this process.
Add PictureBox controls dynamically to the form using C# – Complete Code
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { private PictureBox[] m_pictureBox = {}; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void piccreation() { int i = m_pictureBox.Length; // Make room. Array.Resize(ref m_pictureBox, i + 1); // Create and initialize the control. m_pictureBox[i] = new PictureBox(); var _with1 = m_pictureBox[i]; _with1.Name = "PictureBox" + i.ToString(); _with1.BorderStyle = BorderStyle.Fixed3D; _with1.BackgroundImage = System.Drawing.Image.FromFile("C:\\testimage.jpg"); // Location of Image _with1.BackgroundImageLayout = ImageLayout.Stretch; if (m_pictureBox.Length < 2) { // Position the first one. _with1.SetBounds(8, 8, 118, 94); } else { // Position subsequent controls. _with1.Left = m_pictureBox[i - 1].Left; _with1.Top = m_pictureBox[i - 1].Top + m_pictureBox[i - 1].Height + 4; _with1.Size = m_pictureBox[i - 1].Size; } _with1.Tag = i; this.Controls.Add(m_pictureBox[i]); } private void button1_Click(object sender, EventArgs e) { piccreation(); } } } |
If you have any suggestions or doubts regarding this topic, Add PictureBox control dynamically to the form using C#, feel free to contact us…
Add PictureBox control dynamically to the form using C#







