将图像从列表框加载到图片框

时间:2013-11-03 19:11:11

标签: c# listbox picturebox

我正在尝试通过按钮点击将.JPEG图像从目录加载到ListBox,这是我已经实现的。但是,我需要将这些图像放入PictureBox。有人可以指点我正确的方向吗?这就是我到目前为止所做的。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        DirectoryInfo dinfo = new DirectoryInfo(@"C:\cake");

        FileInfo[] Files = dinfo.GetFiles();

        foreach (FileInfo file in Files)
        {
            listBox1.Items.Add(file.Name);
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        listBox1.Items.Add(@"C:\cake");
    }

    private void pictureBox1_Click(object sender, EventArgs e)
    {
        string[] x = System.IO.Directory.GetFiles(@"C:\cake", "*.jpeg");
        pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

        for (int i = 0; i < x.Length; i++)
        {
            listBox1.Items.Add(x[i]);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

这应该是您正在寻找的是如何使用图像位置在图片框中显示图像。

    pictureBox1.ImageLocation("Image Location");

如果您希望用户能够选择图像,请尝试这样的操作。

        OpenFileDialog dlg = new OpenFileDialog();
        dlg.Filter = "JPEG FILES(*.jpeg)";
        if (dlg.ShowDialog() == DialogResult.OK)
        {
            pictureBox1.ImageLocation(dlg.FileName.ToString());
        }

答案 1 :(得分:0)

应该更像......

    private void button1_Click(object sender, EventArgs e)
    {
        listBox1.Items.Clear();
        DirectoryInfo dinfo = new DirectoryInfo(@"C:\cake");
        FileInfo[] Files = dinfo.GetFiles("*.jpeg");
        listBox1.Items.AddRange(Files);
        listBox1.DisplayMember = "FileName";
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex != -1)
        {
            FileInfo fi = (FileInfo)listBox1.SelectedItem;
            pictureBox1.ImageLocation = fi.FullName;
        }
    }