使用带有PictureBox的组合框下拉列表

时间:2015-11-06 03:13:21

标签: c# winforms

我试图使用组合框下拉列表在图片框中显示图片,其中填充了各种类型的图书;网络,编程,Web。当用户选择特定书籍时,将显示书籍封面的图片。我尝试了很多不同的方法,但似乎没什么用。我有thisGenreComboBox_SelectedIndexChanged所以我想这是if / else if语句的问题。以下是我一直在尝试的内容,我确信它已经开始了。建议?非常感谢!

        //if ((string)thisGenreComboBox.SelectedItem == ("Networking"))
        //if (thisGenreComboBox.Text == "Networking")
        if (thisGenreComboBox.SelectedIndex == 1)
        {
            thisGenrePictureBox.Image = Image.FromFile(@"networkingcover.jpg");
        }

*已编辑*

以下是我最终想出来的,并且完美地满足了我的需求。另外,我将它应用于ListBox,也可以正常工作。

        switch (thisGenreComboBox.SelectedIndex)
        {
            case 0:
                {
                    thisGenrePictureBox.ImageLocation = ("NetworkCover.jpg");
                    break;
                }
            case 1:
                {
                    thisGenrePictureBox.ImageLocation = ("ProgramCover.jpg");
                    break;
                }
            case 2:
                {
                    thisGenrePictureBox.ImageLocation = ("WebProgramCover.jpg");
                    break;
                }
        }

1 个答案:

答案 0 :(得分:1)

有很多方法可以完成这样的任务。

选项1

例如,您可以对图像使用命名约定,例如,如果您有网络,编程和Web书籍,则使用NetworkingCover.jpg,ProgrammingCover.jpg和WebCover.jpg命名图像。

填充你的组合框:

thisGenreComboBox.Items.Add("Networking");
thisGenreComboBox.Items.Add("Programming");
thisGenreComboBox.Items.Add("Web");

然后您可以在comboBox的SelectedIndexChanged事件中使用此代码:

if(thisGenreComboBox.SelectedIndex>-1)
{
    var imageName = string.Format("{0}Cover.jpg", thisGenreComboBox.SelectedItem);
    // I suppose your images are located in an `Image` folder
    // in your application folder and you have this items to your combobox.
    var file = System.IO.Path.Combine(Application.StartupPath, "images" , imageName);
    thisGenrePictureBox.Image = Image.FromFile(file);
}

选项2

作为另一种选择,您可以为您的图书创建一个类:

public class Book
{
    public string Title { get; set; }
    public string Image { get; set; }
    public overrides ToString()
    {
        return this.Title;
    }
}

然后创建你的书并填充你的组合框:

thisGenreComboBox.Items.Add(
    new Book(){Title= "Networking" , Image = "NetworkingCover.jpg"});
thisGenreComboBox.Items.Add(
    new Book(){Title= "Programming" , Image = "ProgrammingCover.jpg"});
thisGenreComboBox.Items.Add(
    new Book(){Title= "Web" , Image = "WebCover.jpg"});

然后在SelectedIndexChnaged组合框的事件中:

if(thisGenreComboBox.SelectedIndex>-1)
{
    var imageName = ((Book)thisGenreComboBox.SelectedItem).Image;

    // I suppose your images are located in an `Image` folder
    // in your application folder and you have this items to your combobox.
    var file = System.IO.Path.Combine(Application.StartupPath, "images" , imageName);
    thisGenrePictureBox.Image = Image.FromFile(file);
}