简体   繁体   中英

Display Image in Picture Box Using Combo Box c#

I'm trying to create a movie ticketing system in c# and if the user selects a movie in the combo box the poster of the movie should be displayed in the picture box. I tried this code but my problem is the choices in the combo box are the path of the image the choices should be the movie title not the path of the image.

 private void Form1_Load(object sender, EventArgs e)
    {
        string[] imgs = Directory.GetFiles(@"C:\Users\me\Documents\C# program\Poster");
        foreach(string file in imgs)
        {
            comboBox1.Items.Add(file);
        }
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string s = comboBox1.SelectedItem.ToString();
        pictureBox1.Image = new Bitmap(s);

How do I display the movie poster using combo box with their movie title?

试试这个:

pictureBox1.Image = Image.FromFile(YourImagePathInStringMode);

If I'm reading your question correctly, right now you have a pictureBox that correctly displays the image of a poster chosen from a comboBox, and the problem you have is that you want the contents of the comboBox to be the title of the movie rather than the location of the poster.

Depending on how your program is set up, the easiest way to answer this is probably to save the string array from your Form1_Load function, create a list of movie titles, and use that as your source for the comboBox Items.

If you are using a pre-defined set of movie titles this should be easy, but if might be tricky if you don't know what the movies are going to be ahead of time- if possible, you could use them as the poster image filenames, and have something like this for your Form1_Load function:

 private string[] posterPaths;
 
 private void Form1_Load(object sender, EventArgs e)
  {
   posterPaths = Directory.GetFiles(@"C:\Users\me\Documents\C#program\Poster");
   foreach(string file in posterPaths)
    {
     //find where the name of the image is in the path
     int index = file.LastIndexOf('\');
     //remove the parts that aren't the movie's name
     string movieName = file.Substring(index,file.Length-index-4)
     comboBox1.Items.Add(movieName);
    }
  }

You could then use the comboBox.SelectedIndex property to figure out which path to use for the imageBox.

Define a image path globally,

private const string imagePath = @"C:\Users\sachithw\Desktop\bikes";

But it's more configurable by adding App.Config file and read the path from there.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
      <add key="imagePath" value="C:\Users\sachithw\Desktop\bikes" />
    </appSettings>
</configuration>

and you can read the path as follows

string imagePath = System.Configuration.ConfigurationManager.AppSettings["imagePath"].ToString();

Full Code,

public partial class Form1: Form {
  private
  const string imagePath = @ "C:\Users\sachithw\Desktop\bikes";
  //string imagePath = System.Configuration.ConfigurationManager.AppSettings["imagePath"].ToString();

  public Form1() {

    this.BackgroundImageLayout = ImageLayout.Stretch;
    InitializeComponent();
  }

  private void Form1_Load(object sender, EventArgs e) {
    DirectoryInfo di = new DirectoryInfo(imagePath);
    FileInfo[] files = di.GetFiles("*.jpg");
    foreach(FileInfo file in files) {
      comboBox1.Items.Add(file.Name);
    }
  }

  private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
    string fileName = comboBox1.SelectedItem.ToString();
    if (pictureBox1.Image != null && pictureBox1 != null) {
      pictureBox1.Image.Dispose();
    }
    string imageFullPath = imagePath + "\\" + fileName;

    pictureBox1.Image = Image.FromFile(imageFullPath);
  }
}

make sure to dispose of the previous picture in the picture box since you are using multiple images in the PictureBox. Otherwise, it will throw the 'System.OutOfMemoryException' excepition.

The following relies on a json file which stores title and image for each movie.

The json file as done here is in the folder with movie images but could be in whatever folder suits you.

Json file where I used available images)

[
  {
    "Title": "Movie 1",
    "ImageName": "checkmark.png"
  },
  {
    "Title": "Movie 2",
    "ImageName": "Mail_16x.png"
  },
  {
    "Title": "Movie 3",
    "ImageName": "upGreenArrow.png"
  }
]

Movie class

namespace MoviesCodeSample
{
    /// <summary>
    /// Represents a single movie, add other
    /// properties if needed before serializing
    /// data in MovieOperations.
    /// </summary>
    public class Movie
    {
        public string Title { get; set; }
        public string ImageName { get; set; }
        /// <summary>
        /// For ComboBox DisplayMember 
        /// </summary>
        /// <returns></returns>
        public override string ToString() => Title;
    }
}

Movie operations

using System.Collections.Generic;
using System.Drawing;
using System.IO;
using Newtonsoft.Json;

namespace MoviesCodeSample
{
    /// <summary>
    /// Movie operations which requires Json.Net NuGet package
    /// or if using .NET Core 5 or higher use System.Text.Json
    /// </summary>
    public class MovieOperations
    {
        /*
         * Mocked up for demonstration, these two properties
         * can be stored under application settings or a json file
         * obtaining your settings rather than done via project properties.
         */
        public static string FolderName = "TODO";
        public static string FileName = Path.Combine(FolderName,"Movies.json");

        /// <summary>
        /// Mockup for demonstration purposes, you would create your own
        /// list, perhaps creating a utility that reads images, allows you
        /// to add descriptions for each movie save back to disk
        /// </summary>
        public static List<Movie> Movies => new List<Movie>()
        {
            new Movie() { Title = "Movie 1", ImageName = "checkmark.png" },
            new Movie() { Title = "Movie 2", ImageName = "Mail_16x.png" },
            new Movie() { Title = "Movie 3", ImageName = "upGreenArrow.png" }
        };

        public static void CreateInitialMoviesJsonFile()
        {
            File.WriteAllText(
                FileName, 
                JsonConvert.SerializeObject(Movies, Formatting.Indented));
        }

        /// <summary>
        /// Read movies from json file, in this case for
        /// demonstration a mocked up json file is created if not exists
        /// which in this case it does not.
        /// </summary>
        /// <returns>movies in json file</returns>
        public static List<Movie> GetMovies()
        {

            if (!File.Exists(FileName))
            {
                CreateInitialMoviesJsonFile();
            }

            return JsonConvert.DeserializeObject<List<Movie>>(
                File.ReadAllText(FileName));

        }

        /// <summary>
        /// Get current movie triggered from selection changed in the ComboBox
        /// on the calling form.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static Image GetMovieImage(string name) 
            => Image.FromFile(Path.Combine(FolderName, name));

    }
}

Form, one PictureBox, one ComboBox

using System;
using System.Windows.Forms;

namespace MoviesCodeSample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Shown += OnShown;
        }

        private void OnShown(object sender, EventArgs e)
        {
            MoviesComboBox.DataSource = MovieOperations.GetMovies();
            MoviesComboBox.SelectedIndexChanged += MoviesComboBoxOnSelectedIndexChanged;
            ShowCurrentMovieImage();
        }

        private void MoviesComboBoxOnSelectedIndexChanged(object sender, EventArgs e)
        {
            ShowCurrentMovieImage();
        }

        private void ShowCurrentMovieImage()
        {
            MoviePictureBox.Image = MovieOperations.GetMovieImage(
                ((Movie)MoviesComboBox.SelectedItem).ImageName);
        }
    }
}

在此处输入图片说明

Try this one:

enter code here

private void button1_Click(object sender, EventArgs e)
    {
 if (comboBox1.SelectedIndex == 0)
 if (comboBox2.SelectedIndex == 0)
 if (comboBox3.SelectedIndex == 0)
    {
        pictureBox1.Image = Image.FromFile(@"C:\Users\Petter\Desktop\test\1.jpg");

}

enter code here

Thank you for your guidens :) i used this and it works great :)

====== SAURABH ======

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM