当前位置: 首页 > news >正文

WPF【10_2】数据库与WPF实战-示例

客户预约关联示例图

MainWindow.xaml 代码
<Window x:Class="WPF_CMS.MainWindow"
    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:WPF_CMS"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <Label Content="客户列表" HorizontalAlignment="Left" Margin="32,22,0,0" VerticalAlignment="Top"/>
    <ListBox Name="customerList" HorizontalAlignment="Left" Height="229" Margin="32,61,0,0" VerticalAlignment="Top" Width="249" SelectionChanged="customerList_SelectionChanged"/>
    <Label Content="预约记录" HorizontalAlignment="Left" Margin="444,22,0,0" VerticalAlignment="Top"/>
    <ListBox Name="appointmentList" HorizontalAlignment="Left" Height="229" Margin="444,61,0,0" VerticalAlignment="Top" Width="249"/>
    <Button Content="删除客户" HorizontalAlignment="Left" Margin="32,306,0,0" VerticalAlignment="Top" Width="249" Click="DeleteCustomer_Click"/>
    <Button Content="取消预约" HorizontalAlignment="Left" Margin="444,306,0,0" VerticalAlignment="Top" Width="249" Click="DeleteAppointment_Click"/>
    <TextBox Name="NameTextBox" HorizontalAlignment="Left" Margin="32,359,0,0" Text="TextBox" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <TextBox Name="IdTextBox" HorizontalAlignment="Left" Margin="322,359,0,0" Text="TextBox" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <TextBox Name="AddressTextBox" HorizontalAlignment="Left" Margin="175,359,0,0" Text="TextBox" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <Label Content="姓名" HorizontalAlignment="Left" Margin="32,331,0,0" VerticalAlignment="Top"/>
    <Label Content="身份证" HorizontalAlignment="Left" Margin="175,333,0,0" VerticalAlignment="Top"/>
    <Label Content="住址" HorizontalAlignment="Left" Margin="322,331,0,0" VerticalAlignment="Top"/>
    <Button Content="添加客户" HorizontalAlignment="Left" Margin="32,382,0,0" VerticalAlignment="Top" Click="AddCustomer_Click"/>
    <DatePicker Name="AppointmentDatePicker" HorizontalAlignment="Left" Margin="467,356,0,0" VerticalAlignment="Top"/>
    <Button Content="预约" HorizontalAlignment="Left" Margin="589,359,0,0" VerticalAlignment="Top" Click="AddAppointment_Click"/>
    <Button Content="更新客户资料" HorizontalAlignment="Left" Margin="112,387,0,0" VerticalAlignment="Top" Click="UpdateCustomer_Click"/>
</Grid>
</Window>

MainWindow.xaml.cs 代码
public partial class MainWindow : Window
{
    private SqlConnection _sqlConnection;
    public MainWindow()
    {
        InitializeComponent();
        string connectionString = "Data Source=localhost;Initial Catalog=course565;Persist Security Info=True;User ID=sa;Password=PaSSword12!;Pooling=False";

        _sqlConnection = new SqlConnection(connectionString);

        ShowCustomers();
    }

    private void ShowCustomers()
    {
        try
        {
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("select * from Customers", _sqlConnection);

            using (sqlDataAdapter)
            {
                DataTable customerTable = new DataTable();
                sqlDataAdapter.Fill(customerTable);

                customerList.DisplayMemberPath = "Name";
                customerList.SelectedValuePath = "Id";
                customerList.ItemsSource = customerTable.DefaultView;
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());
        }
    }

    private void customerList_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        try
        {
            string query = "select * from Appointments join Customers on Appointments.CustomerId = Customers.Id where Customers.Id = @CustomerId";

            var customerId = customerList.SelectedValue;
            if (customerId==null)
            {
                appointmentList.ItemsSource = null;
                return;
            }

            DataRowView selectedItem = customerList.SelectedItem as DataRowView;
            NameTextBox.Text = selectedItem["Name"] as string;
            IdTextBox.Text = selectedItem["IdNnumber"] as string;
            AddressTextBox.Text = selectedItem["Address"] as string;

            SqlCommand sqlCommand = new SqlCommand(query, _sqlConnection);

            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);

            sqlCommand.Parameters.AddWithValue("@CustomerId", customerId);

            using (sqlDataAdapter)
            {
                DataTable appointmentTable = new DataTable();
                sqlDataAdapter.Fill(appointmentTable);

                appointmentList.DisplayMemberPath = "Time";
                appointmentList.SelectedValuePath = "Id";
                appointmentList.ItemsSource = appointmentTable.DefaultView;
            }
        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
    }

    private void DeleteAppointment_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var sql = "delete from Appointments where Id = @AppointmentId";

            var appointmentId = appointmentList.SelectedValue;

            SqlCommand sqlCommand = new SqlCommand(sql, _sqlConnection);
            sqlCommand.Parameters.AddWithValue("@AppointmentId", appointmentId);

            _sqlConnection.Open();
            sqlCommand.ExecuteScalar();
            
        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
        finally
        {
            _sqlConnection.Close();
            customerList_SelectionChanged(null, null);
        }
    }

    private void DeleteCustomer_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            string sqlDeleteAppointment = "delete from Appointments where CustomerId=@CustomerId";
            string sqlDeleteCustomer = "delete from Customers where id=@CustomerId";

            var customerId = customerList.SelectedValue;

            SqlCommand cmd1 = new SqlCommand(sqlDeleteAppointment, _sqlConnection);
            SqlCommand cmd2 = new SqlCommand(sqlDeleteCustomer, _sqlConnection);

            cmd1.Parameters.AddWithValue("@CustomerId", customerId);
            cmd2.Parameters.AddWithValue("@CustomerId", customerId);

            _sqlConnection.Open();
            cmd1.ExecuteScalar();
            cmd2.ExecuteScalar();
        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
        finally
        {
            _sqlConnection.Close();
            ShowCustomers();
            customerList_SelectionChanged(null, null);
        }
    }

    private void AddCustomer_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var sql = "insert into Customers values (@name, @id, @address)";

            SqlCommand sqlCommand = new SqlCommand(sql, _sqlConnection);

            sqlCommand.Parameters.AddWithValue("@name", NameTextBox.Text);
            sqlCommand.Parameters.AddWithValue("@id", IdTextBox.Text);
            sqlCommand.Parameters.AddWithValue("@address", AddressTextBox.Text);

            _sqlConnection.Open();
            sqlCommand.ExecuteScalar();

        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
        finally
        {
            _sqlConnection.Close();
            ShowCustomers();
        }
    }

    private void AddAppointment_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var sql = "insert into Appointments values (@date, @customerId)";

            SqlCommand sqlCommand = new SqlCommand(sql, _sqlConnection);

            sqlCommand.Parameters.AddWithValue("@date", AppointmentDatePicker.Text);
            sqlCommand.Parameters.AddWithValue("@customerId", customerList.SelectedValue);

            _sqlConnection.Open();
            sqlCommand.ExecuteScalar();
        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
        finally
        {
            _sqlConnection.Close();
            customerList_SelectionChanged(null, null);
        }
    }

    private void UpdateCustomer_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var sql = "update Customers set Name=@name, IdNnumber=@idNumber, Address=@address where Id=@customerId";

            SqlCommand sqlCommand = new SqlCommand(sql, _sqlConnection);
            sqlCommand.Parameters.AddWithValue("@name", NameTextBox.Text.Trim());
            sqlCommand.Parameters.AddWithValue("@idNumber", IdTextBox.Text.Trim());
            sqlCommand.Parameters.AddWithValue("@address", AddressTextBox.Text.Trim());
            sqlCommand.Parameters.AddWithValue("@customerId", customerList.SelectedValue);

            _sqlConnection.Open();
            sqlCommand.ExecuteScalar();

        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
        finally
        {
            _sqlConnection.Close();
            ShowCustomers();
        }
    }
}

http://www.xdnf.cn/news/674407.html

相关文章:

  • 中级统计师-统计学基础知识-第七章 回归分析
  • 8.安卓逆向2-frida hook技术-frida环境安装
  • 【IOS】【OC】【应用内打印功能的实现】如何在APP内实现打印功能,连接本地打印机,把想要打印的界面打印成图片
  • 简单网络交换、路由-华三单区域OSPF
  • AGI大模型(34):Advanced RAG之Pre-Retrieval(预检索)优化
  • OpenAI O3惊现算法的自由意识,AGI初现?
  • 在VSTO C#中获取Excel范围内最后一个非空单元格,可以通过以下几种方法实现
  • C标准库函数:字符串操作
  • 【深度学习】7. 深度卷积神经网络架构:从 ILSVRC、LeNet 到 AlexNet、ZFNet、VGGNet,含pytorch代码结构
  • NLP助力非结构化文本抽取:实体关系提取实战
  • 【ASR】基于分块非自回归模型的流式端到端语音识别
  • qt之开发大恒usb3.0相机二
  • Pytorch
  • 题目 3341: 蓝桥杯2025年第十六届省赛真题-抽奖
  • 颠覆传统,智领未来——UMI企业智脑:重新定义企业智能化转型的全新可能
  • 不同电脑同一个网络ip地址一样吗?如何更改
  • ODSA架构与操作-1
  • 【Elasticsearch】_update api的增量更新
  • 企业级RAG技术实战指南:从理论到落地的全景解析
  • .NET用C#设置Excel单元格和工作表的背景
  • AI大模型学习三十、ubuntu安装comfyui
  • vue3简介以及创建第一个vue3工程
  • 无人机仿真环境(3维)附项目git链接
  • 仓颉入门:特性
  • Elasticsearch的运维
  • ubuntu20.04安装CUDA、Cudnn
  • 深度学习————注意力机制模块
  • Milvus向量数据库DML操作实战教程
  • android平台驱动开发(四)--系统属性节点控制GPIO
  • 字节跳动BAGEL-7B-MoT模型开源:多模态AI技术的新范式与行业涟漪