2017-03-21 72 views
0

说我想要listBox1包含一组名。当有人点击其中一个名字时,它会显示listBox2中的姓氏已被选中C#如何从另一个列表框中选择列表框上的对象

我似乎无法让第二个列表框已经被选中。

因此,如果选择listBox1中的第一项,则会选择listBox2中的第一项。等等。

怎么会这样?

下面是一些代码:

private void materialFlatButton3_Click_1(object sender, EventArgs e) 
     { 
      OpenFileDialog OpenFileDialog1 = new OpenFileDialog(); 
      OpenFileDialog1.Multiselect = true; 
      OpenFileDialog1.Filter = "DLL Files|*.dll"; 
      OpenFileDialog1.Title = "Select a Dll File"; 
      if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
      { 
       // put the selected result in the global variable 
       fullFileName = new List<String>(OpenFileDialog1.FileNames); 


       foreach (string s in OpenFileDialog1.FileNames) 
       { 
        listBox2.Items.Add(Path.GetFileName(s)); 
        listBox4.Items.Add(s); 
       } 

      } 
     } 

    private void listBox2_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     string text = listBox2.GetItemText(listBox2.SelectedItem); 
     textBox3.Text = text; 
    } 

在listbox4,它显示的完整路径。在listbox2中,它只显示文件的名称。

我该如何做到这一点,当有人点击列表框2中的文件时,其相应的路径将在列表框4中选择?

+0

使用'DataGridView'有两列'Name'和'全path' – Fabio

+0

@Fabio我希望我的用户只能看到名称,而不是完整的路径。 –

回答

1

创建您自己的类型,用于存储和显示的文件名:

public class FileItem 
{ 
    public FileItem (string path) => FullPath = path; 
    public string FullPath { get; } 
    public override ToString() => Path.GetFileName(FullPath); 
} 

而且这些项目添加到列表框中。这样,您可以存储完整路径并同时显示文件名。


或者只是保留对原始Files数组的引用或将其内容复制到另一个数组。然后从这个数组中获得完整的路径,通过选定的索引,而不是用于存储事物的第二个列表框。

1

创建一个表示显示完整路径和名称的类。
然后使用绑定加载数据到ListBox

public class MyPath 
{ 
    public string FullPath { get; private set; } 
    public string Name ' 
    { 
     get { return Path.GetFileName(s) }    
    } 

    public MyPath(string path) 
    { 
     FullPath = path; 
    } 
} 

// Load and bind it to the ListBox 

var data = OpenFileDialog1.FileNames 
          .Select(path => new MyPath(path)) 
          .ToList(); 

// Name of the property which will be used for displaying text 
listBox1.DisplayMember = "Name"; 
listBox1.DataSource = data; 

private void ListBox1_SelectedValueChanged(object sender, EventArgs e) 
{ 
    var selectedPath = (MyPath)ListBox1.SelectedItem; 
    // Both name and full path can be accesses without second listbox 
    // selectedPath.FullPath 
    // selectedPath.Name 
} 
相关问题