从列表框文件名 C# winform 打开图像

Open image from listbox file name C# winform

我一直在业余时间研究这个,但无济于事。我真的可以用一只手让它工作。

我在 C# 中有一个 winform。我目前正在使用列表框和图片框来显示嵌入的图像资源。我只想用文件名填充列表框,因为完整路径比列表框的宽度长,可以容纳我的表单。

这是我使用的一些代码:

string[] x = System.IO.Directory.GetFiles(@"C:\Users\bassp\Dropbox\VS Projects\WindowsFormsApplication1\WindowsFormsApplication1\Resources\", "*.jpg");
        pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
        foreach (string f in x)
        {
            string entry1 = Path.GetFullPath(f);
            string entry = Path.GetFileNameWithoutExtension(f);
            listBox1.DisplayMember = entry;
            listBox1.ValueMember = entry1;
            listBox1.Items.Add(entry);

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        pictureBox1.ImageLocation = listBox1.SelectedItem.ToString();
    }

如果我用完整路径 (entry1) 填充列表框,除了由于完整路径的长度而无法看到您将要选择的图像名称外,一切都非常顺利。

当我尝试用 (entry) 填充列表框时,只有文件名出现在列表框中,这是理想的,但是,从列表框中选择时图像将不再打开。

我怎样才能让它正常工作?非常感谢帮助。

帕特里克

您通过设置 DisplayMemberValueMember 属性走在正确的轨道上,但您需要进行一些更正,这里可能没有必要。

将原始目录路径存储在一个单独的变量中,然后只需将其与 SelectedIndexChanged 事件中的文件名组合即可获得原始文件路径。

string basePath =
    @"C:\Users\bassp\Dropbox\VS Projects\WindowsFormsApplication1\WindowsFormsApplication1\Resources\";

string[] x = Directory.GetFiles(basePath, "*.jpg");

foreach (string f in x)
{
    listBox1.Items.Add(Path.GetFileNameWithoutExtension(f));
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    pictureBox1.ImageLocation =
        Path.Combine(basePath, listBox1.SelectedItem.ToString()) + ".jpg";
}

Grant answer 对于像这样的简单任务来说完全没问题,但我会解释另一种可能在其他情况下有用的方法。

您可以定义一个 class 来存储您的文件名和路径,例如:

class images
{
    public string filename { get; set; }
    public string fullpath { get; set; }
}

这样,您的代码可以是这样的:

string[] x = System.IO.Directory.GetFiles(@"C:\Users\bassp\Dropbox\VS Projects\WindowsFormsApplication1\WindowsFormsApplication1\Resources\", "*.jpg");
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
List<images> imagelist=new List<images>();
foreach (string f in x)
{
    images img= new images();
    img.fullpath = Path.GetFullPath(f);
    img.filename = Path.GetFileNameWithoutExtension(f);
    imagelist.Add(img);
}
listBox1.DisplayMember = "filename";
listBox1.ValueMember = "fullpath";
listBox1.DataSource = imagelist;

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    pictureBox1.ImageLocation = ((images)listBox1.SelectedItem).fullpath;
}

我还没有测试过,可能有错字,但希望你能明白。