简体   繁体   中英

C# Saving list box items to Array upon button click

On a second form, I have 4 text boxes that when button click "ADD", items add to a single list box in this format

Airport 1 Runway 1 Runway 2 Multiple Runways Airport 2 Runway 1 Runway 2 Multiple Runways Airp............

I have a save button. When I click save, I want to be able to save the Items in the list box in a public array that is accessible by the original form.

My list box is named lbAirports.

This is the code to add to the listbox from the text boxes

Then be able to call the array and place into the list box on form load. Ultimately saving so that it will be saved all the time.

string Airport,Runway1, Runway2, ParallelRwy;

Airport = tbAirport.Text.ToUpper();
Runway1 = tbRunway1.Text;
Runway2 = tbRunway2.Text;
ParallelRwy = tbParallel.Text.ToUpper();


if (Airport == "" || Runway1 == "" || Runway2 == "" || ParallelRwy == "")
{
MessageBox.Show("PLEASE FILL IN ALL BOXES");
}
else
{

lbAirports.Items.Add(string.Format(Input1, Airport, Runway1, Runway2, ParallelRwy));

tbAirport.Clear();
tbRunway1.Clear();
tbRunway2.Clear();
tbParallel.Clear();

tbAirport.Focus();
}

You can save your ListBox items to a local temporary text file, and read them whenever you load your form (as long as you don't mind the file being volatile). If you need the file to be more permanent, you can save it to a different (non-temp) location. I would suggest somewhere within your application root.

Example of how to do this is:

public void SaveToDisk()
{
    StringBuilder sb = new StringBuilder();

    foreach (var item in lbAirports.Items)
    {
        sb.AppendLine(item.ToString());
    }

    File.WriteAllText($"{Path.GetTempPath()}\\airports.txt", sb.ToString());
}

public void LoadFromDisk()
{
    lbAirports.Items.Clear();

    var listContent = File.ReadAllLines($"{Path.GetTempPath()}\\airports.txt");

    foreach (var line in listContent)
    {
        lbAirports.Items.Add(line);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM