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
BackgroundImageLayouttoStretch. - Place 4
PictureBoxcontrols on your form, and set theirVisibleproperties tofalse. Name thempbWinter,pbSpringetc. Set theImageproperty of each by browsing to the image file for each season. - Add a
ComboBoxto your form. Add the items "Winter", "Spring", "Summer" and "Fall". In the combo box's
SelectedIndexChangedevent handler, check the box'sTextproperty with aswitchstatement, 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...
}
}
加载中,请稍侯......
精彩评论