[英]how to add the selected item from a listbox to list <string> in c#
[英]How to delete a selected listbox item from both the listbox and the original list in c#
我在刪除用戶在我的文本框中輸入然后存儲在列表框中的列表中的數據時遇到問題。 我知道如何刪除列表框中的所選項目,但是當我單擊我的按鈕以顯示列表中的所有內容時,剛刪除的所選項目仍在列表中。
這是我的代碼,用於刪除列表框中的選定項目:
for (int i = 0; i < VehicleListBox.SelectedItems.Count; i++)
VehicleListBox.Items.Remove(VehicleListBox.SelectedItems[i]);
我的清單在一個名為company的類中,該清單稱為車輛。 我大部分時間都在四處尋找答案,但似乎找不到。 我還應該提到這是一個通用列表。
好的,我測試了。
foreach (string thing in listBox1.SelectedItems){
myList.remove(thing);
}
因此,據我了解,您正在使用getDetails
來獲取列表,然后將它們一個接一個地添加到VehicleListBox
。
一種選擇是從List
刪除選定的項目,然后相應地更新ListBox。
您添加一個簡單的方法來執行此操作:
private void UpdateListBox(List<string> vehicles);
將“ List”替換為您使用的類型。
另外,您是否嘗試過綁定ListBox
的ItemsSource
?
在WPF中(例如):
<ListBox Name=ExampleListBox, ItemsSource={Binding} />
內碼:
ExampleListBox.DataContext = myList;
填充列表后,最好在Window_Loaded方法中使用。 如有必要,請在列表更改時進行更新。
就您所了解的類設計而言,我在WPF項目中編寫了以下代碼。 我在表單中添加了一個名為“ listbox1”的列表框和一個按鈕。 我相信以下代碼可以滿足您的要求,或者至少可以指導您找到答案。
public class Company
{
public List<Vehicle> Vehicles;
public Company()
{
Vehicles = new List<Vehicle>() { new Vehicle(1), new Vehicle(2), new Vehicle(3) };
}
}
public class Vehicle
{
private string _vehicleNum;
public Vehicle(int num)
{
_vehicleNum = "Vehicle" + num.ToString();
}
public string getDetails()
{
return _vehicleNum;
}
}
Company ACompany = new Company();
public MainWindow()
{
InitializeComponent();
foreach(Vehicle v in ACompany.Vehicles)
listbox1.Items.Add(v.getDetails());
}
private void Button_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < listbox1.SelectedItems.Count; i++)
{
foreach(Vehicle v in ACompany.Vehicles)
{
if (String.Equals(v.getDetails(), listbox1.SelectedItems[i].ToString()))
{
ACompany.Vehicles.Remove(v);
break;
}
}
listbox1.Items.Remove(listbox1.SelectedItems[i]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.