基于ArrayList实现Windows Forms应用的手机号增删与本地文件存储
Hey there! Let's walk through building this Windows Forms app step by step—since you already have your Person class, we’re off to a great start. I’ll assume your Person class has basic properties like Name and Age (adjust the code below to match your actual class).
First, let’s outline the core components we’ll need:
- A few TextBox controls to input user info (e.g.,
txtName,txtAge) - Two Button controls:
btnAdd(to save a new user) andbtnDelete(to remove a selected user) - A ListBox control (
listBoxUsers) to display all saved users (makes selecting for deletion easier) - A global
ArrayListto hold your Person objects in memory - A text file path (we’ll use the app’s current directory for simplicity)
Step 1: Define Your Person Class (Example)
If your Person class looks something like this, we can build off it:
public class Person { public string Name { get; set; } public int Age { get; set; } // Constructor public Person(string name, int age) { Name = name; Age = age; } // Override ToString() to display nicely in ListBox public override string ToString() { return $"{Name} (Age: {Age})"; } }
The ToString() override is key—it lets the ListBox show a readable version of each Person instead of the default class name.
Step 2: Set Up Global Variables & Form Load Event
In your Form’s code-behind, declare these global variables:
private ArrayList personList = new ArrayList(); private string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "users.txt");
The filePath points to a users.txt file in your app’s running directory (easy to find and manage).
Next, add a Form Load event to load existing data from the txt file into the ArrayList when the app starts:
private void Form1_Load(object sender, EventArgs e) { // Check if the file exists before trying to read it if (File.Exists(filePath)) { string[] lines = File.ReadAllLines(filePath); foreach (string line in lines) { // Split each line into name and age (we'll use comma as separator) string[] parts = line.Split(','); if (parts.Length == 2 && int.TryParse(parts[1], out int age)) { personList.Add(new Person(parts[0], age)); } } // Update the ListBox with loaded users UpdateListBox(); } } // Helper method to refresh the ListBox with current ArrayList data private void UpdateListBox() { listBoxUsers.Items.Clear(); foreach (Person p in personList) { listBoxUsers.Items.Add(p); } }
Step 3: Implement the "Add" Button Functionality
Double-click your btnAdd button to generate the click event, then add this code:
private void btnAdd_Click(object sender, EventArgs e) { // Get input from text boxes string name = txtName.Text.Trim(); string ageInput = txtAge.Text.Trim(); // Validate input (don't let empty name or invalid age pass) if (string.IsNullOrEmpty(name) || !int.TryParse(ageInput, out int age)) { MessageBox.Show("Please enter a valid name and age!"); return; } // Create new Person object Person newPerson = new Person(name, age); // Add to ArrayList personList.Add(newPerson); // Write to txt file (append the new line) File.AppendAllText(filePath, $"{name},{age}{Environment.NewLine}"); // Refresh ListBox UpdateListBox(); // Clear text boxes for next input txtName.Clear(); txtAge.Clear(); }
We use AppendAllText here to add the new user to the end of the txt file—no need to rewrite the whole file every time we add someone.
Step 4: Implement the "Delete" Button Functionality
Double-click your btnDelete button and add this code:
private void btnDelete_Click(object sender, EventArgs e) { // Make sure a user is selected in the ListBox if (listBoxUsers.SelectedItem == null) { MessageBox.Show("Please select a user to delete!"); return; } // Get the selected Person object Person selectedPerson = (Person)listBoxUsers.SelectedItem; // Remove from ArrayList personList.Remove(selectedPerson); // Rewrite the entire txt file with the updated ArrayList // (Simpler for beginners than trying to delete a single line) List<string> lines = new List<string>(); foreach (Person p in personList) { lines.Add($"{p.Name},{p.Age}"); } File.WriteAllLines(filePath, lines); // Refresh ListBox UpdateListBox(); }
Rewriting the entire file is straightforward for beginners—no need to mess with finding and deleting specific lines. For small datasets (which is likely your case), this works perfectly.
Bonus Tips for Beginners
- Error Handling: Wrap file operations in
try-catchblocks to handle unexpected issues (like permission errors). For example:try { File.AppendAllText(filePath, $"{name},{age}{Environment.NewLine}"); } catch (Exception ex) { MessageBox.Show($"Error saving user: {ex.Message}"); } - Switch to Generic Lists Later: Once you’re comfortable with ArrayList, consider using
List<Person>instead—it’s type-safe and avoids the need for casting (like(Person)listBoxUsers.SelectedItem). - Test Edge Cases: Try adding duplicate names, invalid ages, or deleting the last user to make sure everything works as expected.
内容的提问来源于stack exchange,提问作者Georges Ridgmont

