c# - UWP。如何将数据传递到我的数据库然后填充网格?
问题描述
我在使用 UWP 时遇到了一些困难,想知道是否有人可以提供帮助?C♯在这里很新。
基本上我有一个添加员工的页面,我认为输入的数据在逻辑上应该发送到一个名为“Person”的类,然后再添加到数据库中(但我知道什么哈哈哈!)。然后数据库需要在主页面上填充一个网格。
所以,主要的两个问题是,如何让 Person 类中的数据填充数据库并依次填充主页上的网格?以及如何从不同的页面添加到班级人员?
这是我尝试的地方:
这就是我的 Person 类:
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,
// TaxCode = "LC455"
// },
// 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, 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 ee){}
}
}
当你要将 Person 的数据插入 DataBase 时,我以 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 的更多详细信息,您可以参考此文档。
另外,当你想在 Grid 中显示新数据时,建议使用ObservableCollection类而不是 List,当你从这个类中插入或删除数据时,它会自动更新 UI。
ObservableCollection<Person> persons;
public MainPage()
{
this.InitializeComponent();
persons = new ObservableCollection<Person>();
......
}
如何从不同的页面添加到班级人员
您可以声明一个公共静态属性来表示 MainPage 实例,然后您可以直接调用公共方法来添加一个新的 Person 类。您可以将 NavigationCacheMode 设置为 Enabled,在这种情况下,当您返回 MainPage 时,数据将被缓存。例如:
主页.cs:
public MainPage()
{
this.InitializeComponent();
......
this.NavigationCacheMode = NavigationCacheMode.Enabled;
Current = this;
}
public static MainPage Current;
public void addMethod(Person p)
{
persons.Add(p);
}
第二页.cs:
private void AddNewData(object sender, RoutedEventArgs e)
{
//First add data to database like mainpage does
MainPage.Current.addMethod(person);
}
推荐阅读
- vue.js - Vitepress 自定义主题,不同页面的多种布局
- ios - 无法使用 Swift 5.3.0 为 iOS 模拟器构建 React Native 应用程序
- windows - 在 ec2 windows 中运行的进程
- python - 在 VS Code 中创建 python 文件
- java - 不好的做法或不赞成使用逗号分隔大小写?切换 case 语句 Java
- reactjs - React - 方法不更新 DOM
- typescript - 为什么打字稿将未知范围缩小到永远不会在可到达的条件块内?
- sql - 将 OVER (PARTITION BY ...) 与 GROUPING SETS 结合起来?
- scala - sacla 中的 private[wikipedia] 是什么意思?
- javascript - Res.send 和如果功能混淆..?