WPF+EF Core+DataGrid实现数据展示——增删查改方法

效果图:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

一、创建WPF窗体程序

创建步骤(vs);
在这里插入图片描述

二、通过NuGet程序包管理器安装如下包:

在这里插入图片描述

在这里插入图片描述
安装成功效果:
在这里插入图片描述

三、新建文件夹,命名为Model、添加student实体类、studentContext数据库关系映射类。如图

在这里插入图片描述
student实体类:

using System;
using System.Collections.Generic;
using System.Text;

namespace CRUDWPF.Model
{
    public class Students//学生类
    {
        //学生ID
        public int Id { get; set; }
        //学生名称
        public string  StudentName { get; set; }
        //学生性别
        public string  Gender { get; set; }
        //学生出生年月
        public DateTime Birthday { get; set; }
        //学生地址
        public string Address { get; set; }
        //家长电话
        public string PatriarchTel { get; set; }  
    }
}

studentContext数据库关系映射类:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;

namespace CRUDWPF.Model
{
    public class StudentContext : DbContext
    {
        //映射类
        public DbSet<Students> GetStudents { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //数据库链接,创建
            optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=StudentDB;Integrated Security=True");
        }
    }
}

四、通过EF core反向构建数据库:

通过程序包管理控制台:
在这里插入图片描述
执行操作:
在这里插入图片描述
执行成功后会构建好数据库和下图文件夹:
在这里插入图片描述

五、新建文件夹Dal构建StuDal类(方法集)

在这里插入图片描述
StuDal类:

using CRUDWPF.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CRUDWPF.Dal
{
    public class StuDal
    {
        public static StudentContext studentContext = new StudentContext();
        //查询所有学生数据
        public static List<Students> GetStudent()
        {
            return studentContext.GetStudents.ToList();
        }
        //添加新的学生信息
        public static void InsertStu(Students students)
        {
            studentContext.GetStudents.Add(students);
            studentContext.SaveChanges();
        }
        //修改学生信息
        public static void UpdateStu(Students students)
        {
            var id = studentContext.GetStudents.Find(students.Id);
            var entry = studentContext.Entry(id);
            entry.CurrentValues.SetValues(students);
            entry.Property(p => p.Id).IsModified = false;
            studentContext.SaveChanges();
        }
        //删除学生信息
        public static void DeleteStu(int ids)
        {
            Students student = studentContext.GetStudents.FirstOrDefault(p => p.Id == ids);
            studentContext.GetStudents.Remove(student);
            studentContext.SaveChanges();
        }
        //学生信息关键字查询
        public static List<Students> SetKeyStudent(string StuName)
        {
            return studentContext.GetStudents.Where(p=>p.StudentName.Contains(StuName)).ToList();
        }
        //学生信息ID查询
        public static Students SetIdStudent(int ids)
        {
            return studentContext.GetStudents.FirstOrDefault(p => p.Id == ids);
        }
    }
}

六、构建数据显示页面

项目右键新建项(页面命名:MainWindow):
在这里插入图片描述
在这里插入图片描述
页面前台代码:

<Window x:Class="CRUDWPF.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:CRUDWPF"
        mc:Ignorable="d"
        Title="MainWindow" Height="451" Width="800">
    <Grid Margin="0,0,0,3">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <TextBox HorizontalAlignment="Left" Margin="93,10,0,0" Text="" Name="StuKey" TextWrapping="Wrap" VerticalAlignment="Top" Width="244" Height="30" FontSize="18"/>
        <Label Content="关键字:" HorizontalAlignment="Left" Margin="32,10,0,0" VerticalAlignment="Top" Height="30" Width="57"></Label>
        <Button Content="查询" Name="SetStudent" HorizontalAlignment="Left" Margin="362,10,0,0" VerticalAlignment="Top" Height="30" Width="60" Click="SetStudent_Click"/>
        <Button Content="刷新" HorizontalAlignment="Right" Name="Refresh" Margin="0,10,112,0" VerticalAlignment="Top" Height="30" Width="60" RenderTransformOrigin="-3.308,0.523" Click="Refresh_Click"/>
        <Button Content="添加" HorizontalAlignment="Right" Name="AddStu" Margin="0,10,30,0" VerticalAlignment="Top" Height="30" Width="59" Click="AddStu_Click"/>
        <Rectangle Height="1" Margin="-352,59,-348,0" Stroke="Black" VerticalAlignment="Top" Width="1500"/>
        <DataGrid x:Name="StudentShow" AutoGenerateColumns="False" CanUserAddRows="False" ColumnWidth="*"  Grid.Column="0" Height="338" VerticalAlignment="Top" Margin="10,83,10,0" MinRowHeight="30" ColumnHeaderHeight="30">
            <DataGrid.Columns>
                <DataGridTextColumn Header="学生ID" Binding="{Binding Id}"/>
                <DataGridTextColumn Header="学生姓名" Binding="{Binding StudentName}"/>
                <DataGridTextColumn Header="性别" Binding="{Binding Gender}"/>
                <DataGridTextColumn Header="出生年月" Binding="{Binding Birthday}"/>
                <DataGridTextColumn Header="家庭住址" Binding="{Binding Address}"/>
                <DataGridTextColumn Header="家长电话" Binding="{Binding PatriarchTel}"/>
                <DataGridTemplateColumn Header="操作">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Grid>
                                <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
                                    <Button Width="40" Height="20" Content="编辑" Tag="{Binding Id}" FontSize="10" Click="Button_Click"></Button>
                                    <Button Width="40" Height="20" Name="DeleteDetail"  Tag="{Binding Id}" Margin="10,0,0,0" Content="删除" FontSize="10" Click="DeleteDetail_Click"></Button>
                                </StackPanel>
                            </Grid>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

后台代码:
在这里插入图片描述

using CRUDWPF.Dal;
using CRUDWPF.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CRUDWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            List<Students> ds = StuDal.GetStudent().ToList();
            StudentShow.ItemsSource = ds;
        }
        //查询数据
        private void SetStudent_Click(object sender, RoutedEventArgs e)
        {
            string key = StuKey.Text;
            List<Students> ds = StuDal.SetKeyStudent(key).ToList();
            StudentShow.ItemsSource = ds;
        }
        //新增弹窗
        private void AddStu_Click(object sender, RoutedEventArgs e)
        {
            StudentAdd isw = new StudentAdd();
            isw.Title = "添加";
            isw.Owner = this;//设置父窗口,这样可以在父窗口中居中
            isw.ShowDialog();//模式,弹出!
        }
        //删除详情
        private void DeleteDetail_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult dr = MessageBox.Show("确定要删除吗 ?,删除后不可恢复", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
            if (dr == MessageBoxResult.OK)
            {
                Button btn = sender as Button;
                if (btn != null)
                {
                    int id = Convert.ToInt32(btn.Tag);
                    StuDal.DeleteStu(id);
                }
            }
            List<Students> ds = StuDal.GetStudent().ToList();
            StudentShow.ItemsSource = ds;
        }
        //刷新页面数据
        private void Refresh_Click(object sender, RoutedEventArgs e)
        {
            List<Students> ds = StuDal.GetStudent().ToList();
            StudentShow.ItemsSource = ds;
        }
        //编辑信息
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            if (btn != null)
            {
                int id = Convert.ToInt32(btn.Tag);
                UpdateStu isw = new UpdateStu(id);
                isw.Title = "编辑";
                isw.Owner = this;//设置父窗口,这样可以在父窗口中居中
                isw.ShowDialog();//模式,弹出!
            }
        }
    }
}

七、新增数据页面构建

页面名称:StudentAdd
前台代码:

<Window x:Class="CRUDWPF.StudentAdd"
        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:CRUDWPF"
        mc:Ignorable="d"
        Title="StudentAdd" Height="413" Width="657">
    <Grid Margin="0,0,0,-5">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Label Content="新增学生信息" HorizontalAlignment="Left" Margin="306,14,0,0" VerticalAlignment="Top" FontSize="16"/>
        <Label Content="姓名:" HorizontalAlignment="Left" Margin="111,50,0,0" VerticalAlignment="Top" Height="30" FontSize="16"/>
        <TextBox HorizontalAlignment="Left" Name="StuName" Margin="173,51,0,0" Text="" TextWrapping="Wrap" VerticalAlignment="Top" Width="393" Height="30" FontSize="16"/>
        <Label Content="性别:" HorizontalAlignment="Left" Margin="111,92,0,0" VerticalAlignment="Top" Height="30" FontSize="16"/>
        <ComboBox HorizontalAlignment="Left" Name="StuGender" Margin="173,94,0,0" VerticalAlignment="Top" Width="393" FontSize="16" Height="30">
            <ComboBoxItem Content="" Selector.IsSelected="True"></ComboBoxItem>
            <ComboBoxItem Content="" ></ComboBoxItem>
        </ComboBox>
        <Label Content="出生年月:" HorizontalAlignment="Left" Margin="76,138,0,0" VerticalAlignment="Top" Height="30" FontSize="16"/>
        <DatePicker HorizontalAlignment="Left" Name="StuBirthday" Margin="174,138,0,0" VerticalAlignment="Top" Height="30" Width="392" FontSize="16"/>
        <Label Content="家庭住址:" HorizontalAlignment="Left" Margin="76,183,0,0" VerticalAlignment="Top" Height="30" FontSize="16"/>
        <TextBox HorizontalAlignment="Left" Name="StuAddress" Margin="173,184,0,0" Text="" TextWrapping="Wrap" VerticalAlignment="Top" Width="393" Height="30" FontSize="16"/>
        <Label Content="家长电话:" HorizontalAlignment="Left" Margin="77,228,0,0" VerticalAlignment="Top" Height="30" FontSize="16"/>
        <TextBox HorizontalAlignment="Left" Name="StuPatriarchTel" Margin="174,228,0,0" Text="" TextWrapping="Wrap" VerticalAlignment="Top" Width="393" Height="30" FontSize="16"/>
        <Button Content="新增" HorizontalAlignment="Left" Name="AddNewStu" Margin="174,307,0,0" VerticalAlignment="Top" Height="29" Width="70" Click="AddNewStu_Click"/>
        <Button Content="取消" HorizontalAlignment="Left" Name="Addout" Margin="328,307,0,0" VerticalAlignment="Top" Height="29" Width="70" Click="Addout_Click"/>

    </Grid>
</Window>

后台代码:

using CRUDWPF.Model;
using CRUDWPF.Dal;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CRUDWPF
{
    /// <summary>
    /// StudentAdd.xaml 的交互逻辑
    /// </summary>
    public partial class StudentAdd : Window
    {
        public StudentAdd()
        {
            WindowStartupLocation = WindowStartupLocation.CenterOwner;//在父窗口中居中
            InitializeComponent();
        }
        //取消新增
        private void Addout_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        //新增学生信息
        private void AddNewStu_Click(object sender, RoutedEventArgs e)
        {
            //学生写姓名
            string Name = StuName.Text;
            //学生性别
            string Gender = StuGender.Text;
            //出生年月
            string Birthday = StuBirthday.Text;
            //家庭住址
            string Address = StuAddress.Text;
            //家长电话
            string PatriarchTel = StuPatriarchTel.Text;
            if (Name!=""&&Gender!="" && Birthday !="" && Address !="" && PatriarchTel !="")
            {
                Students student = new Students();
                student.StudentName = Name;
                student.Gender = Gender;
                student.Birthday = DateTime.Parse(Birthday);
                student.Address = Address;
                student.PatriarchTel = PatriarchTel;
                StuDal.InsertStu(student);
                this.Close();//关闭当前窗口
                }
            else
            {
                MessageBoxResult dr = MessageBox.Show("数据填写不完整", "提示", MessageBoxButton.OK, MessageBoxImage.Question);
            }
        }
    }
}

八、构建修改信息页面

注意:tag跨页面传值
页面名称:UpdateStu
前台代码

<Window x:Class="CRUDWPF.UpdateStu"
        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:CRUDWPF"
        mc:Ignorable="d"
        Title="UpdateStu" Height="406" Width="692">
    <Grid Margin="0,0,10,-5">
        <Label Content="修改学生信息" HorizontalAlignment="Left" Margin="306,14,0,0" VerticalAlignment="Top" FontSize="16"/>
        <Label Content="姓名:" HorizontalAlignment="Left" Margin="111,50,0,0" VerticalAlignment="Top" Height="30" FontSize="16"/>
        <TextBox HorizontalAlignment="Left" Name="StuName" Margin="173,51,0,0" Text="" TextWrapping="Wrap" VerticalAlignment="Top" Width="393" Height="30" FontSize="16"/>
        <Label Content="性别:" HorizontalAlignment="Left" Margin="111,92,0,0" VerticalAlignment="Top" Height="30" FontSize="16"/>
        <ComboBox HorizontalAlignment="Left" Name="StuGender" Margin="173,94,0,0" VerticalAlignment="Top" Width="393" FontSize="16" Height="30">
            <ComboBoxItem Content="" ></ComboBoxItem>
            <ComboBoxItem Content="" ></ComboBoxItem>
        </ComboBox>
        <Label Content="出生年月:" HorizontalAlignment="Left" Margin="76,138,0,0" VerticalAlignment="Top" Height="30" FontSize="16"/>
        <DatePicker HorizontalAlignment="Left" Name="StuBirthday" Margin="174,138,0,0" VerticalAlignment="Top" Height="30" Width="392" FontSize="16"/>
        <Label Content="家庭住址:" HorizontalAlignment="Left" Margin="76,183,0,0" VerticalAlignment="Top" Height="30" FontSize="16"/>
        <TextBox HorizontalAlignment="Left" Name="StuAddress" Margin="173,184,0,0" Text="" TextWrapping="Wrap" VerticalAlignment="Top" Width="393" Height="30" FontSize="16"/>
        <Label Content="家长电话:" HorizontalAlignment="Left" Margin="77,228,0,0" VerticalAlignment="Top" Height="30" FontSize="16"/>
        <TextBox HorizontalAlignment="Left" Name="StuPatriarchTel" Margin="174,228,0,0" Text="" TextWrapping="Wrap" VerticalAlignment="Top" Width="393" Height="30" FontSize="16"/>
        <Button Content="修改" HorizontalAlignment="Left" Name="UpdateNewStu" Margin="174,307,0,0" VerticalAlignment="Top" Height="29" Width="70" Click="UpdateNewStu_Click"/>
        <Button Content="取消" HorizontalAlignment="Left" Name="Updateout" Margin="328,307,0,0" VerticalAlignment="Top" Height="29" Width="70" Click="Updateout_Click"/>
    </Grid>
</Window>

后台代码:

using CRUDWPF.Dal;
using CRUDWPF.Model;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CRUDWPF
{
    /// <summary>
    /// UpdateStu.xaml 的交互逻辑
    /// </summary>
    public partial class UpdateStu : Window
    {
        public static int ids;
        public UpdateStu(int id)
        {
            ids = id;
            WindowStartupLocation = WindowStartupLocation.CenterOwner;//在父窗口中居中
            InitializeComponent();
            Students student=StuDal.SetIdStudent(ids);
            if (student!=null)
            {
                StuName.Text = student.StudentName;
                StuGender.SelectedIndex = int.Parse(student.Gender == "男" ? "0" : "1");
                StuBirthday.Text = student.Birthday.ToString("yyyy/MM/dd");
                StuAddress.Text = student.Address;
                StuPatriarchTel.Text = student.PatriarchTel;
            }
        }
        //修改数据
        private void UpdateNewStu_Click(object sender, RoutedEventArgs e)
        {
            //学生写姓名
            string Name = StuName.Text;
            //学生性别
            string Gender = StuGender.Text;
            //出生年月
            string Birthday = StuBirthday.Text;
            //家庭住址
            string Address = StuAddress.Text;
            //家长电话
            string PatriarchTel = StuPatriarchTel.Text;
            if (Name != "" && Gender != "" && Birthday != "" && Address != "" && PatriarchTel != "")
            {
                Students student = new Students();
                student.Id = ids;
                student.StudentName = Name;
                student.Gender = Gender;
                student.Birthday = DateTime.Parse(Birthday);
                student.Address = Address;
                student.PatriarchTel = PatriarchTel;
                StuDal.UpdateStu(student);
                this.Close();//关闭当前窗口
            }
            else
            {
                MessageBoxResult dr = MessageBox.Show("数据填写不完整", "提示", MessageBoxButton.OK, MessageBoxImage.Question);
            }
        }
        //取消修改
        private void Updateout_Click(object sender, RoutedEventArgs e)
        {
            this.Close();//关闭页面
        }
    }
}

WPF 项目中实现数据库连接是开发桌面应用程序时的常见需求。使用 C# 编写 WPF 应用程序,可以通过多种方式与数据库进行交互,包括直接使用 ADO.NET、Entity Framework 或者 ORM 框架等。 ### 数据库连接的基本步骤 1. **选择合适的数据库驱动** 根据目标数据库类型(如 MySQL、SQL Server、Oracle 等),安装相应的 .NET 提供程序。例如: - MySQL:需要安装 [MySQL Connector/Net](https://dev.mysql.com/downloads/connector/net/)。 - Oracle:需要安装 [Oracle Data Provider for .NET (ODP.NET)](https://www.oracle.com/database/technologies/dotnet-odac-downloads.html)。 - SQL Server:通常自带 `System.Data.SqlClient`,无需额外安装。 2. **添加引用** 在 WPF 项目中,确保引用了数据库访问所需的 DLL 文件。例如: - 对于 MySQL,添加对 `MySql.Data.dll` 的引用。 - 对于 Oracle,添加对 `Oracle.DataAccess.dll` 的引用。 - 对于 SQL Server,使用内置的 `System.Data.SqlClient`。 3. **配置连接字符串** 连接字符串包含数据库服务器地址、端口、数据库名称、用户名和密码等信息。连接字符串可以硬编码在代码中,也可以存储在 `App.config` 或 `Settings.settings` 文件中以提高灵活性。 示例 MySQL 连接字符串: ```xml <connectionStrings> <add name="MyMySqlConnection" connectionString="Server=localhost;Database=mydb;Uid=root;Pwd=123456;" providerName="MySql.Data.MySqlClient" /> </connectionStrings> ``` 4. **编写数据访问代码** 使用 ADO.NET 实现数据库连接和查询操作的核心类包括 `MySqlConnection`、`MySqlCommand`、`MySqlDataAdapter` 和 `DataTable`。 示例代码展示如何连接 MySQL 并执行 SELECT 查询: ```csharp using System; using System.Data; using MySql.Data.MySqlClient; using System.Windows; namespace WpfAppMySqlExample { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); LoadDataFromMySql(); } private void LoadDataFromMySql() { string connectionString = "Server=localhost;Database=mydb;Uid=root;Pwd=123456;"; string query = "SELECT * FROM students"; using (MySqlConnection conn = new MySqlConnection(connectionString)) { try { conn.Open(); MySqlCommand cmd = new MySqlCommand(query, conn); MySqlDataAdapter adapter = new MySqlDataAdapter(cmd); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); // 假设有一个 DataGrid 控件用于显示数据 dataGrid.ItemsSource = dataTable.DefaultView; } catch (Exception ex) { MessageBox.Show("数据库连接失败: " + ex.Message); } } } } } ``` 5. **绑定数据到 UI 元素** WPF 支持强大的数据绑定机制,可以将查询结果绑定到 `DataGrid`、`ListBox`、`ComboBox` 等控件上,提升用户体验。 6. **异常处理与资源管理** 在数据库操作过程中应始终使用 `try...catch` 块捕获异常,并使用 `using` 语句确保连接和其他资源被正确释放。 ### 使用 Entity Framework 进行数据库连接 对于更复杂的业务逻辑,推荐使用 Entity Framework(EF)作为 ORM 工具。它简化了数据库操作并提高了开发效率。 #### EF Core 配置示例(以 MySQL 为例) 1. 安装 NuGet 包: ``` Install-Package Pomelo.EntityFrameworkCore.MySql ``` 2. 创建 DbContext 类: ```csharp using Microsoft.EntityFrameworkCore; public class MyDbContext : DbContext { public DbSet<Student> Students { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySql("Server=localhost;Database=mydb;Uid=root;Pwd=123456;", ServerVersion.AutoDetect("Server=localhost;Database=mydb;Uid=root;Pwd=123456;")); } } ``` 3. 定义实体类: ```csharp public class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } ``` 4. 在 WPF 中调用 EF 查询数据: ```csharp var context = new MyDbContext(); var students = context.Students.ToList(); dataGrid.ItemsSource = students; ``` ### 总结 WPF 连接数据库实现方法多样,可以根据项目复杂度和团队技术栈选择合适的方式。无论是使用 ADO.NET 还是 Entity Framework,都需要关注连接字符串的安全性、代码的可维护性以及数据绑定的灵活性。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值