UWP如何将数据传递到数据库然后填充网格?

如何解决UWP如何将数据传递到数据库然后填充网格?

我在使用UWP时遇到了一些困难,想知道是否有人可以提供帮助?这里对C♯来说是很新的东西。

基本上,我有一个用于添加雇员的页面,我认为输入的数据应该从逻辑上发送到一个名为“ Person”的类,然后再添加到数据库中(但是我知道哈哈!)。然后,数据库需要在主页上填充网格。

因此,主要的两个问题是,如何使Person类中的数据填充DB,并依次填充主页上的网格?以及如何从其他页面向班级添加人员?

这就是我要尝试的地方:

这是我的Person Class的内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestApp2
{
    using static DB;
    class Person 
    {
            public int PersonId { get; set; }
            public int DepartmentId { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Position { get; set; }
            public string Address { get; set; }
            public double PayratePH { get; set; }
            public double Holiday { get; set; }
            public string TaxCode { get; set; }

        private List<String> Grab_Entries()
        {
            List<String> entries = new List<string>();
            using (SqliteConnection db = new SqliteConnection("Filename=sqliteSample.db"))
            {
                db.Open();
                SqliteCommand selectCommand = new SqliteCommand("SELECT First_Name from EmployeeTable",db);
                SqliteDataReader query;
                try
                {
                    query = selectCommand.ExecuteReader();
                }
                catch (SqliteException)
                {
                    //Handle error
                    return entries;
                }
                while (query.Read())
                {
                    entries.Add(query.GetString(0));
                    
                }
                db.Close();
            }
            return entries;
            
        }
        
    }

} 

这是我的数据库课程:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;

namespace TestApp2
{
    public static class DB
    {
        private static SuspendingEventHandler App_Suspending;

        public static void database()
        {
            Application.Current.Suspending += new SuspendingEventHandler(App_Suspending);
            using (SqliteConnection db = new SqliteConnection("Filename=sqliteSample.db"))
            {
                //Creation of the database table
                db.Open();
                String tableCommand1 = "CREATE TABLE IF NOT EXISTS EmployeeTable (Employee_ID INTEGER PRIMARY KEY AUTOINCREMENT,First_Name NVARCHAR(20) NULL,Last_Name NVARCHAR(40) NULL,Address NVARCHAR(50) NULL,Position NVARCHAR(20) NULL,Pay_Rate DOUBLE NULL,Tax_Code NVARCHAR(10) NULL,Sex NVARCHAR(20),NI NVACHAR(10),Emergency_Details NVARCHAR(100)";
                
                SqliteCommand createTable = new SqliteCommand(tableCommand1,db);
                
                try
                {
                    createTable.ExecuteReader();
                }
                catch (SqliteException)
                {
                    //Do nothing
                }
            }
        }
    }
} 

最后是我的主页。注释掉的部分是我在测试是否可以填充xaml网格(如果有帮助的话,我正在使用社区开发网格?https://docs.microsoft.com/en-us/windows/communitytoolkit/controls/datagrid_guidance/datagrid_basics

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;



// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace TestApp2
{
    

    public class Department
    {
        public int DepartmentId { get; set; }
        public string DepartmentName { get; set; }
    }

    //public class Person
    //{
    //    public int PersonId { get; set; }
    //    public int DepartmentId { get; set; }
    //    public string FirstName { get; set; }
    //    public string LastName { get; set; }
    //    public string Position { get; set; }
    //    public string Address { get; set; }
    //    public double PayratePH { get; set; }
    //    public double Holiday { get; set; }
    //    public string TaxCode { get; set; }


    //}
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {

        public List<Department> Departments { get; set; }
        List<Person> persons;

        public MainPage()
        {
            this.InitializeComponent();
            persons = new List<Person>();

        //    Departments = new List<Department>
        //{
        //    new Department {DepartmentId = 1,DepartmentName = "R&D"},//    new Department {DepartmentId = 2,DepartmentName = "Finance"},//    new Department {DepartmentId = 3,DepartmentName = "IT"}
        //};



        //    persons = new List<Person>
        //{
        //    new Person
        //    {
        //        PersonId = 1,DepartmentId = 3,FirstName = "Ronald",LastName = "Rumple",//        Position = "Network Administrator",Address = "14 Malkie Avenue",Holiday = 20,//        TaxCode = "LC455"
        //    },//    new Person
        //    {
        //        PersonId = 2,DepartmentId = 1,FirstName = "Brett",LastName = "Banner",//        Position = "Software Developer",Address = "4/L Long Terrace",PayratePH = 12.95,Holiday = 12.5,//    new Person
        //    {
        //        PersonId = 3,DepartmentId = 2,FirstName = "Alice",LastName = "Anderson",//        Position = "Accountant",Address = "56 Hemming Way",PayratePH = 10,Holiday = 19.9,//        TaxCode = "LC455"
        //    }
        //};
        }

        private async void searchEmployee_Click(object sender,RoutedEventArgs e)
        {
            await new MessageDialog("Test").ShowAsync();

        }

        private void rota_Click(object sender,RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(Rota));
        }

        private void emailEmployee_Click(object sender,RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(email));
        }

        private void addEmployee_Click(object sender,RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(AddEmployee));
        }
    }
}

解决方法

如何使Person类中的数据填充数据库,并依次填充主页上的网格

您创建的tableCommand1字符串并不完整,您需要像这样修改它:String tableCommand1 = "CREATE TABLE IF NOT EXISTS EmployeeTable (Employee_ID INTEGER PRIMARY KEY AUTOINCREMENT,First_Name NVARCHAR(20) NULL,Last_Name NVARCHAR(40) NULL,Address NVARCHAR(50) NULL,Position NVARCHAR(20) NULL,Pay_Rate DOUBLE NULL,Tax_Code NVARCHAR(10) NULL,Sex NVARCHAR(20),NI NVACHAR(10),Emergency_Details NVARCHAR(100))";

用于创建数据库的完整代码为:

public async static void database()
{
    await ApplicationData.Current.LocalFolder.CreateFileAsync("sqliteSample.db",CreationCollisionOption.OpenIfExists);
    string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path,"sqliteSample.db");
    using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
    {
        //Creation of the database table
        db.Open();
        String tableCommand1 = "CREATE TABLE IF NOT EXISTS EmployeeTable (Employee_ID INTEGER PRIMARY KEY AUTOINCREMENT,Emergency_Details NVARCHAR(100))";

        SqliteCommand createTable = new SqliteCommand(tableCommand1,db);

        try
        {
            createTable.ExecuteReader();
        }
        catch (SqliteException ee){}
    }
}

当您要将Person的数据插入数据库时​​,我以first_name为例:

private void InsertData(object sender,RoutedEventArgs e)
{
   string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path,"sqliteSample.db");
    using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
    {
        db.Open();

        SqliteCommand insertCommand = new SqliteCommand();
        insertCommand.Connection = db;

        // Use parameterized query to prevent SQL injection attacks
        insertCommand.CommandText = "INSERT INTO EmployeeTable VALUES (NULL,@First_Name);";
        insertCommand.Parameters.AddWithValue("@First_Name","Hello");

        insertCommand.ExecuteReader();
        db.Close();
    }
}

有关如何使用sqlite的更多详细信息,可以参考此document

此外,当您想向网格显示新数据时,建议使用ObservableCollection类而不是List,当您从此类中插入或删除数据时,它将自动更新UI。 / p>

ObservableCollection<Person> persons;

public MainPage()
{
    this.InitializeComponent();
    persons = new ObservableCollection<Person>();
    ......
}

如何从其他页面添加人员

您可以声明一个公共静态属性来表示MainPage实例,然后可以直接调用公共方法来添加新的Person类。您可以将NavigationCacheMode设置为Enabled,在这种情况下,当您返回MainPage时,将缓存数据。例如:

MainPage.cs:

public MainPage()
{
    this.InitializeComponent();
    ......
    this.NavigationCacheMode = NavigationCacheMode.Enabled;

    Current = this;
}

public static MainPage Current;

public void addMethod(Person p) 
{
    persons.Add(p);
}

SecondPage.cs:

private void AddNewData(object sender,RoutedEventArgs e)
{
    //First add data to database like mainpage does
    MainPage.Current.addMethod(person);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-