Combobox how to get the selected item to show a theme
I'm doing a tic tac toe game and I am trying to add a combo box that will change the applications background based on what the person selects right now I have summer, spring, fall, winter and the images are in the bin/debug 开发者_运维知识库folder how can I get this to work I don't know where to start and the tutorials are a bit confusing. Could you please help me
It isn't exactly clear what you are asking. Assuming you've got bitmap files with names like "spring.png" etc in your bin\Debug folder, this ought to work:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
comboBox1.Items.AddRange(new string[] { "Spring", "Summer", "Fall", "Winter" });
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
string folder = Application.StartupPath;
string theme = (string)comboBox1.Items[comboBox1.SelectedIndex];
string path = System.IO.Path.Combine(folder, theme + ".png");
Image newImage = new Bitmap(path);
if (this.BackgroundImage != null) this.BackgroundImage.Dispose();
this.BackgroundImage = newImage;
}
}
There are many ways to do this. This is probably the simplest:
- Set your main form's
BackgroundImageLayout
toStretch
. - Place 4
PictureBox
controls on your form, and set theirVisible
properties tofalse
. Name thempbWinter
,pbSpring
etc. Set theImage
property of each by browsing to the image file for each season. - Add a
ComboBox
to your form. Add the items "Winter", "Spring", "Summer" and "Fall". In the combo box's
SelectedIndexChanged
event handler, check the box'sText
property with aswitch
statement, and set the appropriate back image with code like this:this.BackgroundImage = pbWinter.Image; // etc. ...
Update: Here's how to do the switch statement:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBox1.Text)
{
case "Winter":
this.BackgroundImage = pbWinter.Image;
break;
case "Spring":
this.BackgroundImage = pbSpring.Image;
break;
// etc...
}
}
精彩评论