You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForm应用:文本文件读写及ComboBox数据加载问题求助

解决方案

1. 整理数据结构(推荐用类替代多数组)

用User类统一存储用户信息,比多个独立数组更易维护:

public class User
{
    public string Name { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public DateTime Birthday { get; set; }
}

2. 优化保存代码(自动释放资源+固定日期格式)

替换原有保存方法,避免文件未关闭问题,同时让日期格式更稳定:

// 声明全局集合存储所有用户,替代Names/Phone等数组
private List<User> users = new List<User>();

private void button3_Click(object sender, EventArgs e)
{
    // 将当前输入的用户信息加入集合
    User newUser = new User
    {
        Name = txtName.Text,
        Phone = txtPhone.Text,
        Email = txtEmail.Text,
        Birthday = dateTimePickerBirthday.Value
    };
    users.Add(newUser);

    // 写入文件,using会自动释放文件资源
    using (TextWriter txt = new StreamWriter(@"D:\data.txt"))
    {
        foreach (var user in users)
        {
            txt.WriteLine(user.Name);
            txt.WriteLine(user.Phone);
            txt.WriteLine(user.Email);
            txt.WriteLine(user.Birthday.ToString("yyyy-MM-dd")); // 固定格式避免解析错误
        }
    }
    MessageBox.Show("Data saved in data.txt file on drive D!", "Caution!", 0);
}

3. 编写文件读取方法

按你保存的格式(每4行对应一个用户)解析数据:

private List<User> LoadUsersFromFile()
{
    List<User> loadedUsers = new List<User>();
    string filePath = @"D:\data.txt";

    if (!File.Exists(filePath))
        return loadedUsers;

    string[] allLines = File.ReadAllLines(filePath);

    // 每4行一组读取用户信息,防止文件内容不完整导致索引越界
    for (int i = 0; i < allLines.Length; i += 4)
    {
        if (i + 3 >= allLines.Length)
            break;

        User user = new User();
        user.Name = allLines[i].Trim();
        user.Phone = allLines[i + 1].Trim();
        user.Email = allLines[i + 2].Trim();

        // 安全解析日期,避免格式错误崩溃
        if (DateTime.TryParse(allLines[i + 3].Trim(), out DateTime birthday))
        {
            user.Birthday = birthday;
        }
        else
        {
            user.Birthday = DateTime.MinValue; // 解析失败设默认值
        }

        loadedUsers.Add(user);
    }

    return loadedUsers;
}

4. 窗体加载时填充ComboBox

在窗体Load事件中调用读取方法,把用户姓名加载到ComboBox:

private void Form1_Load(object sender, EventArgs e)
{
    users = LoadUsersFromFile();

    // 绑定ComboBox,设置显示用户姓名
    comboBox1.DisplayMember = "Name";
    comboBox1.DataSource = users;
}

5. 处理ComboBox选中事件,显示完整信息

选中姓名时自动填充对应信息到控件:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboBox1.SelectedItem is User selectedUser)
    {
        // 替换成你实际用来显示信息的控件名
        txtPhone.Text = selectedUser.Phone;
        txtEmail.Text = selectedUser.Email;
        dateTimePickerBirthday.Value = selectedUser.Birthday;
    }
}

内容的提问来源于stack exchange,提问作者Lia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 20:31:04