繁体   English   中英

从列表框文件名 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)填充列表框,除了由于完整路径的长度而无法看到您将选择的图像名称之外,事情会非常顺利。

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

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

帕特里克

您通过设置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 答案完全没问题,但我将解释另一种可能在其他情况下有用的方法。

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

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

我还没有测试过它,也许它有任何错字,但我希望你能明白。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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