从列表框文件名C#winform

时间:2016-03-10 16:44:27

标签: 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)填充列表框,除了无法看到由于完整路径的长度而将要选择的图像名称之外,其他工作非常顺利。

当我尝试使用(条目)填充列表框时,只有文件名出现在列表框中,这是合乎需要的,但是,从列表框中选择的图像将不再打开。

如何才能使其正常工作?非常感谢帮助。

帕特里克

2 个答案:

答案 0 :(得分:1)

您可以通过设置DisplayMemberValueMember属性来确定正确的方向,但是您需要进行一些更正,这里可能没有必要。< / p>

将原始目录路径存储在单独的变量中,然后将其与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";
}

答案 1 :(得分:1)

对于像这样的简单任务,格兰特答案是完全可以的,但我将解释在其他情况下可能有用的另一种方法。

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

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

我没有测试过它,也许它有任何拼写错误,但我希望你明白这一点。