2017-03-21 116 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 
} 
相關問題