I end up with all the deliveries in the following array
public static ArrayList myDeliveries = new ArrayList();
It is loaded into开发者_JS百科 the listview. I select an item as follows:
iDeliverySelected = lstDeliveryDetails.SelectedItems[0].Index;
I am struggling to understand how I can select an item and use a delete button to remove it from the text file?
Someone might have a smarter solution, but I think you're going to have to generate the entire text file after the user has made changes via the GUI.
That's how you remove the selected item:
lstDeliveryDetails.Items.RemoveAt(iDeliverySelected);
If you need to save a set of objects to disk, then read them back (and do that repeatedly as the objects change), I would say you need to look into serialization and deserialization.
This is essentially what you are doing already manually, but there are ways to automate this and make it easier.
You can use the XMLSerializer
class to do this, but you will have to mark your Delivery
objects with the SerializableAttribute
if they are not yet marked as such.
Edit: (following comments and update to question)
If, before calling saveFile()
, you remove the selected item from the ArrayList, it will get saved without that item:
myDeliveries.RemoveAt(selectedIndex);
//Or
myDeliveries.Remove(selectedObject);
You have not shown how you populate the myDeliveries or lstDeliveryDetails, so I will make some assumptions. When you delete an item from lstDeliveryDetails, you also need to delete the same item from myDeliveries, using the Remove method. When you have finished making the changes to the list, you persist it to file using a StreamWriter:
using (StreamWriter sw = new StreamWriter("../../MealDeliveries.txt"))
{
foreach (object obj in myDeliveries)
{
sw.WriteLine(((Delivery)obj).DeliveryName);
// etc
}
}
If you use a List collection instead of ArrayList, you do not need to cast to (Delivery) either, you can just do "foreach (Delivery delivery in myDeliveries)".
精彩评论