【问题标题】:Display Image in Picture Box Using Combo Box c#使用组合框 c# 在图片框中显示图像
【发布时间】:2021-12-13 07:58:18
【问题描述】:

我正在尝试在 C# 中创建一个电影票务系统,如果用户在组合框中选择一部电影,则该电影的海报应该显示在图片框中。我试过这段代码,但我的问题是组合框中的选择是图像的路径,选择应该是电影标题而不是图像的路径。

 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);

如何使用带有电影标题的组合框显示电影海报?

【问题讨论】:

  • 请检查答案并验证。

标签: c# combobox picturebox


【解决方案1】:

试试这个:

pictureBox1.Image = Image.FromFile(YourImagePathInStringMode);

【讨论】:

    【解决方案2】:

    如果我正确阅读了您的问题,那么现在您有一个图片框,可以正确显示从组合框中选择的海报图像,而您遇到的问题是您希望组合框的内容是 电影的标题而不是海报的位置。

    根据程序的设置方式,最简单的回答方法可能是保存 Form1_Load 函数中的字符串数组,创建电影标题列表,并将其用作组合框项的来源。

    如果您使用的是一组预定义的电影标题,这应该很容易,但如果您不提前知道电影的内容可能会很棘手 - 如果可能的话,您可以将它们用作海报图像文件名,并为您的 Form1_Load 函数提供类似的内容:

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

    然后您可以使用 comboBox.SelectedIndex 属性来确定要为 imageBox 使用的路径。

    【讨论】:

      【解决方案3】:

      全局定义图片路径,

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

      但通过添加App.Config 文件并从那里读取路径,它更易于配置。

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

      你可以读取路径如下

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

      完整代码,

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

      请务必处理图片框中的前一张图片,因为您在 PictureBox 中使用多个图像。否则会抛出'System.OutOfMemoryException' 异常。

      【讨论】:

        【解决方案4】:

        以下依赖于存储每部电影的标题和图像的 json 文件。

        此处完成的 json 文件位于包含电影图像的文件夹中,但可以位于任何适合您的文件夹中。

        我使用可用图像的 Json 文件)

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

        电影课

        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;
            }
        }
        

        电影运营

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

        表格,一个PictureBox,一个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);
                }
            }
        }
        

        【讨论】:

          【解决方案5】:

          试试这个:

          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

          感谢您的指导 :) 我用过这个,效果很好 :)

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-08-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-06-25
            • 1970-01-01
            • 2014-06-01
            相关资源
            最近更新 更多