I have to develop Windows C# application, using Visual Studio 2008. It have dynamical to create pictureboxes, to add image in it, and to move picturebox to some X position.
So, I have windows form with next components:
- button, with title “Add new”
- Combobox
- Text Field
- another button, with title “Set position”.
Also, I have one folder with several images (png files) in it.
So, when I click on first button it have to create new PictureBox, and to add name of Picturebox into ComboBox.
After that, I can choose one PictureBox from it’s list in combobox, and to move it to X position I entered into TextBox.
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 DynamicComponents
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int imgCounter = 0;
/*
* Create pictureboxes and add images
*/
private void button1_Click(object sender, EventArgs e)
{
PictureBox pb = new PictureBox();
pb.Name = "PictureBox" + (++imgCounter);
pb.Size = new Size(100, 100);
pb.Image = Image.FromFile(@"C:\slike\" + imgCounter.ToString() + ".png");
this.Controls.Add(pb);
comboBox1.Items.Add(pb.Name);
}
/*
* Move PictureBox on X position I entered into textfield
* */
private void button2_Click(object sender, EventArgs e)
{
// help!!!
}
}
}
You have already (successfully it seems) managed to dynamically create new
PictureBoxcontrols, add them to the form and also show their name in theComboBox.When you click the button, you will somehow need to “navigate” from the selected item in the
ComboBoxto aPictureBox. One simple way of achieving this is to use the fact that the list in aComboBoxtakes any object, not only strings. So, instead of addingpb.Nameto theComboBox, you can addpbitself. This will create one small problem though; instead of the name of the picture box, the combo box will now showSystem.Windows.Forms.PictureBox. This can be fixed by setting theDisplayMemberproperty of theComboBox(this property tells theComboBoxwhich property value to fetch from each object and use for display):So, you could set the
DisplayMemberproperty in the constructor ofForm1:Then, when creating the
PictureBoxcontrols, add them to theComboBox:Now you can easily pick up the
PictureBoxreference from theComboBoxinbutton2_Click: