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

C# WPF 如何配置Update按钮实现表格行内容修改与保存功能

WPF 编辑弹窗实现步骤

步骤1:新建编辑窗口

在你的项目上右键 -> 添加 -> 新建项 -> 选择「窗口(WPF)」,命名为EditStudentWindow.xaml

1.1 编辑EditStudentWindow.xaml布局

<Window x:Class="Sort_a_list.EditStudentWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="编辑学生信息" Height="300" Width="400" WindowStartupLocation="CenterOwner">
    <Grid Margin="15">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="80"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        
        <TextBlock Grid.Row="0" Grid.Column="0" Text="姓名:" VerticalAlignment="Center"/>
        <TextBox x:Name="TxtName" Grid.Row="0" Grid.Column="1" Margin="0 5" Text=""/>
        
        <TextBlock Grid.Row="1" Grid.Column="0" Text="年龄:" VerticalAlignment="Center"/>
        <TextBox x:Name="TxtAge" Grid.Row="1" Grid.Column="1" Margin="0 5" Text=""/>
        
        <TextBlock Grid.Row="2" Grid.Column="0" Text="性别:" VerticalAlignment="Center"/>
        <TextBox x:Name="TxtGender" Grid.Row="2" Grid.Column="1" Margin="0 5" Text=""/>
        
        <TextBlock Grid.Row="3" Grid.Column="0" Text="专业:" VerticalAlignment="Center"/>
        <TextBox x:Name="TxtMajor" Grid.Row="3" Grid.Column="1" Margin="0 5" Text=""/>
        
        <TextBlock Grid.Row="4" Grid.Column="0" Text="分类:" VerticalAlignment="Center"/>
        <TextBox x:Name="TxtClassification" Grid.Row="4" Grid.Column="1" Margin="0 5" Text=""/>
        
        <StackPanel Grid.Row="6" Grid.Column="0" Grid.ColumnSpan="2" Orientation="Horizontal" HorizontalAlignment="Right">
            <Button x:Name="BtnSave" Content="保存" Width="80" Margin="0 0 10 0" Click="BtnSave_Click"/>
            <Button x:Name="BtnCancel" Content="取消" Width="80" Click="BtnCancel_Click"/>
        </StackPanel>
    </Grid>
</Window>

1.2 编写EditStudentWindow.xaml.cs后台代码

using System.Windows;

namespace Sort_a_list
{
    public partial class EditStudentWindow : Window
    {
        // 用来接收和返回编辑的学生对象
        public Student EditStudent { get; set; }

        public EditStudentWindow(Student student)
        {
            InitializeComponent();
            EditStudent = student;
            // 初始化输入框值
            TxtName.Text = student.name;
            TxtAge.Text = student.age.ToString();
            TxtGender.Text = student.gender;
            TxtMajor.Text = student.major;
            TxtClassification.Text = student.classification;
        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            // 简单校验年龄是否为数字
            if (!int.TryParse(TxtAge.Text, out int age))
            {
                MessageBox.Show("年龄请输入数字");
                return;
            }
            // 把输入的值回写到学生对象
            EditStudent.name = TxtName.Text;
            EditStudent.age = age;
            EditStudent.gender = TxtGender.Text;
            EditStudent.major = TxtMajor.Text;
            EditStudent.classification = TxtClassification.Text;

            DialogResult = true;
            Close();
        }

        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }
    }
}

步骤2:修改主窗口代码

替换你原有MainWindow.xaml.cs的全部代码即可:

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;

namespace Sort_a_list
{
    public partial class MainWindow : Window
    {
        // 全局学生列表
        private List<Student> _studentList;
        // 数据文件路径,提取成常量方便修改
        private const string DataFilePath = @"C:\Users\justi\Documents\2021 Self Study\WPF C#\Samples.txt";
        
        public class Student
        {
            public string name { get; set; }
            public int age { get; set; }
            public string gender { get; set; }
            public string major { get; set; }
            public string classification { get; set; }
        }

        public MainWindow()
        {
            InitializeComponent();
            LoadStudentData();
        }

        // 加载学生数据方法,单独抽出来方便复用
        private void LoadStudentData()
        {
            _studentList = new List<Student>();
            try
            {
                using (StreamReader sr = new StreamReader(DataFilePath))
                {
                    string line;
                    char[] sep = { ',' };
                    // 跳过表头
                    string header = sr.ReadLine();
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] words = line.Split(sep);
                        if (words.Length >=5)
                        {
                            _studentList.Add(new Student() 
                            { 
                                name = words[0], 
                                age = int.Parse(words[1]), 
                                gender = words[2], 
                                major = words[3], 
                                classification = words[4] 
                            });
                        }
                    }
                }
                sort.ItemsSource = _studentList;
            }
            catch(Exception e)
            {
                MessageBox.Show($"文件读取失败:{e.Message}");
            }
        }

        // Update按钮点击事件
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // 判断是否选中了行
            if (sort.SelectedItem is Student selectedStudent)
            {
                EditStudentWindow editWindow = new EditStudentWindow(selectedStudent);
                // 弹出编辑窗口
                if (editWindow.ShowDialog() == true)
                {
                    // 编辑完成后刷新DataGrid显示
                    sort.Items.Refresh();
                    // 保存修改到文件
                    SaveStudentDataToFile();
                }
            }
            else
            {
                MessageBox.Show("请先选中要编辑的行");
            }
        }

        // 把修改后的学生列表写回文件
        private void SaveStudentDataToFile()
        {
            try
            {
                using (StreamWriter sw = new StreamWriter(DataFilePath))
                {
                    // 先写表头
                    sw.WriteLine("name,age,gender,major,classification");
                    // 逐行写学生数据
                    foreach (var student in _studentList)
                    {
                        sw.WriteLine($"{student.name},{student.age},{student.gender},{student.major},{student.classification}");
                    }
                }
                MessageBox.Show("修改已保存");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败:{ex.Message}");
            }
        }
    }
}

优化建议

如果想要修改后DataGrid自动刷新、不需要手动调用Items.Refresh(),可以把List<Student>改成ObservableCollection<Student>,同时给Student类实现INotifyPropertyChanged接口即可,也可以根据业务需要给输入框添加更多校验规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 02:54:09