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 PictureBox
controls, add them to the form and also show their name in the ComboBox
.
When you click the button, you will somehow need to "navigate" from the selected item in the ComboBox
to a PictureBox
. One simple way of achieving this is to use the fact that the list in a ComboBox
takes any object, not only strings. So, instead of adding pb.Name
to the ComboBox
, you can add pb
itself. This will create one small problem though; instead of the name of the picture box, the combo box will now show System.Windows.Forms.PictureBox
. This can be fixed by setting the DisplayMember
property of the ComboBox
(this property tells the ComboBox
which property value to fetch from each object and use for display):
So, you could set the DisplayMember
property in the constructor of Form1
:
public Form1()
{
InitializeComponent();
comboBox1.DisplayMember = "Name"; // use the Name property from items
// in the list when displaying them
}
Then, when creating the PictureBox
controls, add them to the ComboBox
:
comboBox1.Items.Add(pb);
Now you can easily pick up the PictureBox
reference from the ComboBox
in button2_Click
:
private void button2_Click(object sender, EventArgs e)
{
PictureBox selectedPictureBox = comboBox1.SelectedItem as PictureBox;
if (selectedPictureBox != null)
{
// use selectedPictureBox to set the appropriate property values
}
}
精彩评论