[英]C# How to select an object on a listbox from another listbox
說我希望listBox1
包含一組名字。 當某人單擊這些名字之一時,它將在listBox2
顯示姓氏,並且已經被選中 。
我似乎無法選擇第二個列表框。
因此,如果選擇了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中,它僅顯示文件名。
當有人單擊listbox2中的文件時,如何在listbox4中選擇相應的路徑,我該如何做呢?
創建您自己的類型以存儲和顯示文件名:
public class FileItem
{
public FileItem (string path) => FullPath = path;
public string FullPath { get; }
public override ToString() => Path.GetFileName(FullPath);
}
並將這些項目添加到列表框中。 這樣,您可以存儲完整路徑並同時顯示文件名。
或者,僅保留對原始Files數組的引用,或將其內容復制到另一個數組。 然后從該數組通過選定的索引獲取完整路徑,而不是從另一個用於存儲內容的列表框獲取完整路徑。
創建一個代表完整路徑和名稱以供顯示的類。
然后使用將加載的數據綁定到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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.