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

标签 c# winforms listbox picturebox

闲暇时我一直在研究这个问题,但没有结果。我真的可以用手让它工作。

我有一个 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";
}

关于c# - 从列表框文件名打开图像 C# winform,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35922374/

相关文章:

c# - 通过特定属性过滤类实例的属性并调用属性的方法

c# - 从 C# 调用非托管 .dll 的性能

c# - 如何定期更新 Windows 窗体应用程序的远程数据库连接密码?

c# - 模拟鼠标移动

silverlight - 根据 Silverlight 中的绑定(bind)属性隐藏列表框项目中的内容

c# - 我正在尝试在 C# 中删除列表框中的空项

c# - 如何解决数据集错误 - 数据集不支持 'union' 或 'list' 作为 simpleType

.net - 清除程序的所有处理程序的通用函数?

c# - ListBox 插入颜色项目

c# - 为什么我的类(class)将一个集合保存到数据库而不是另一个?