2015-11-06 35 views
1

我試圖在使用組合框下拉列表的圖片框中顯示圖片,該圖片填充了各種類型的書籍;網絡,編程,網絡。當用戶選擇特定的書籍時,將顯示書籍封面的圖片。我嘗試了一堆不同的方法,但似乎沒有任何工作。我有thisGenreComboBox_SelectedIndexChanged,所以我想這是一個if/else if語句的問題。以下是我一直在嘗試的方式,我確信它已經過時了。建議?非常感謝!在PictureBox中使用組合框下拉列表

 //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

有很多方法可以完成這樣的任務。

選項1

例如,你可以使用一個命名約定爲您的圖像,例如,如果你有網絡,編程和網頁書名與NetworkingCover.jpg,ProgrammingCover.jpg和你的圖片WebCover.jpg。

填寫您的組合框:

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

正如你可以創建一個類的另一種選擇:

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

然後你就可以在組合框的SelectedIndexChanged事件中使用此代碼爲您的書:

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); 
} 
+0

禮,感謝您的時間和精力在幫助​​我與我的問題。 – Heavy

+0

@Heavy如果你點擊答案附近的複選標記將答案標記爲已接受,那將會很棒:) –