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

WPF项目中点击ListView项删除SQLite数据库记录的问题

问题描述

我正在为大学项目开发一款商务排班应用(Business Rota App),使用WPF和SQLite数据库。我希望点击ListView中对应的项时,删除数据库中的对应记录。我尝试使用EmployeeList.SelectedItem在数据库中查找该项,但因它是一个对象而总是报错。我在网上找不到将SelectedItem转换为ListView中存储的文本数据的方法,无法用db.Find查找数据并删除。我是不是漏掉了一行简单的代码?谢谢。

XAML代码

<Window x:Class="Business_Rota_Application.StaffMaintenance"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Business_Rota_Application"
        mc:Ignorable="d"
        Title="StaffMaintenance" Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>

        <ListView Grid.Column="0" Margin="232,32,232,110" Name="EmployeeList" Grid.RowSpan="3" x:FieldModifier="public">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="EmployeeID" DisplayMemberBinding="{Binding EmployeeID}" Width="100"></GridViewColumn>
                    <GridViewColumn Header="FirstName" DisplayMemberBinding="{Binding FirstName}" Width="100"></GridViewColumn>
                    <GridViewColumn Header="LastName" DisplayMemberBinding="{Binding LastName}" Width="100"></GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
        <Button Content="Add" HorizontalAlignment="Left" Margin="262,51,0,0" Grid.Row="2" VerticalAlignment="Top" Click="Add_Click" Height="34" Width="76" x:Name="btn_Add"/>
        <Button Content="Update" HorizontalAlignment="Center" Grid.Row="2" VerticalAlignment="Top" Height="34" Width="76" Margin="0,51,0,0" x:Name="btn_Update" Click="btn_Update_Click"/>
        <Button Content="Remove" HorizontalAlignment="Left" Margin="465,51,0,0" Grid.Row="2" VerticalAlignment="Top" Height="34" Width="76" x:Name="btn_Remove" Click="btn_Remove_Click"/>
        <Button Content="Close" HorizontalAlignment="Center" Margin="0,95,0,22" Grid.Row="2" Click="Button_Click"/>
    </Grid>
</Window>

原始C#删除代码

private void btn_Remove_Click(object sender, RoutedEventArgs e)
{

    try
    {
        using (AppDBContext db = new AppDBContext())
        {
            var findEmployee = db.Employees.Find(EmployeeList.SelectedItems);
            db.Employees.Remove(findEmployee);
            db.SaveChanges();
            MessageBox.Show("Data successfully Removed.", "Employee App", MessageBoxButton.OK);
            EmployeeList.Items.Clear();
            PopulateEmployeeData();
        }
    }
    catch (Exception)
    {
        MessageBox.Show("Error in deleting record", "Employee App", MessageBoxButton.OK, MessageBoxImage.Error);
    }         
}
解决方案

核心问题是误用了SelectedItems(复数集合)而非SelectedItem(单个选中对象),且未正确转换实体类型,无需提取文本数据,直接操作绑定的实体即可,修正后的代码如下:

private void btn_Remove_Click(object sender, RoutedEventArgs e)
{
    try
    {
        // 先判断是否选中有效项
        if (EmployeeList.SelectedItem == null)
        {
            MessageBox.Show("请先选择要删除的员工", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            return;
        }

        // 将选中项安全转换为Employee实体类型
        var selectedEmployee = EmployeeList.SelectedItem as Employee;
        if (selectedEmployee == null) return;

        using (AppDBContext db = new AppDBContext())
        {
            // 通过主键查找数据库中的对应记录
            var targetEmployee = db.Employees.Find(selectedEmployee.EmployeeID);
            if (targetEmployee != null)
            {
                db.Employees.Remove(targetEmployee);
                db.SaveChanges();
                MessageBox.Show("数据已成功删除。", "员工管理", MessageBoxButton.OK);
                // 刷新ListView数据
                EmployeeList.Items.Clear();
                PopulateEmployeeData();
            }
            else
            {
                MessageBox.Show("未找到该员工的数据库记录", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"删除失败:{ex.Message}", "员工管理", MessageBoxButton.OK, MessageBoxImage.Error);
    }         
}

关键修正说明

  • 替换SelectedItems为SelectedItem:前者是选中项的集合,后者是单个选中对象,符合你的删除需求
  • 直接转换实体类型:SelectedItem本身就是你绑定到ListView的Employee对象,无需提取文本,用as关键字安全转换即可
  • 增加空值判断:避免未选中项时触发空引用异常
  • 优化异常提示:显示具体错误信息,便于调试排查

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:01:21