WindowsPhone8 数据库增删改查
今天第一次在博客园发表文章,如果有的地方写的不对,还请大家指出!
1.这就是一个简单wp8数据库增删改查

1.创建数据表Person
[Table]
public class Person : INotifyPropertyChanged, INotifyPropertyChanging
{
/// <summary>
/// 编号
/// </summary>
private int id;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int Id
{
get { return id; }
set
{
if (id != value)
{
NotifyPropertyChanging("Id");
id = value;
NotifyPropertyChanged("Id");
}
}
}
/// <summary>
/// 姓名
/// </summary>
private string name;
[Column]
public string Name
{
get { return name; }
set
{
if (name != value)
{
NotifyPropertyChanging("Name");
name = value;
NotifyPropertyChanged("Name");
}
}
} /// <summary>
/// 年龄
/// </summary>
private int age;
[Column]
public int Age
{
get { return age; }
set
{
if (age != value)
{
NotifyPropertyChanging("Age");
age = value;
NotifyPropertyChanged("Age");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// 用来通知页面表的字段数据产生了改变
/// </summary>
/// <param name="propertyName"></param>
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangingEventHandler PropertyChanging;
/// <summary>
/// 用来通知数据上下文表的字段数据将要产生改变
/// </summary>
/// <param name="propertyName"></param>
private void NotifyPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}
}
2.创建数据库的DataContext对象
public class PersonContext : DataContext
{ public PersonContext(string connection)
: base(connection)
{
} public Table<Person> Person;
}
3.创建页面数据绑定的集合
public class PersonCollection : INotifyPropertyChanged
{
private ObservableCollection<Person> personList;
public ObservableCollection<Person> PersonList
{
get { return personList; }
set
{
if (personList != value)
{
personList = value;
NotifyPropertyChanged("PersonList");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
4.在程序加载过程中进行创建数据库
//如果数据库不存在就创建一个数据库
using (PersonContext dbPerson = new PersonContext(ConnectString))
{
if (dbPerson.DatabaseExists() == false)
{
dbPerson.CreateDatabase();
}
}
5.实现person增删改查操作
MainPage.xaml.cs代码:
public partial class MainPage : PhoneApplicationPage
{
private PersonContext PersonDB;
private PersonCollection PersonCollection = new PersonCollection();
// 构造函数
public MainPage()
{
InitializeComponent();
//连接数据并初始化一个Context对象
PersonDB = new PersonContext(App.ConnectString);
var person = from Person p in PersonDB.Person select p;//获取Person表中所有的数据
PersonCollection.PersonList = new ObservableCollection<Person>(person);//将查询的结果返回到页面数据绑定的集合里面
this.DataContext = PersonCollection;//赋值给当前页面的DataContext用于数据绑定
}
private int? ConvertTo(object obj)
{
try
{
return Convert.ToInt32(obj);
}
catch { }
return null;
}
private void BtnOk_OnClick(object sender, RoutedEventArgs e)
{
string age = this.Age.Text.Trim();
string name = this.Name.Text.Trim();
if (string.IsNullOrEmpty(age) || string.IsNullOrEmpty(name))
{
MessageBox.Show("姓名和年龄都不能为空!");
}
else if (ConvertTo(age) == null)
{
MessageBox.Show("您输入的年龄不合法!"); }
else
{
if (State.Count > && State["person"] != null)//判断State中是否有Key为person的值,如果有则进行编辑,否则就进行新增
{
Person p = State["person"] as Person;
p.Name = name;
p.Age = Convert.ToInt32(ConvertTo(age));
PersonDB.SubmitChanges();//保存数据库的改变
PersonCollection.PersonList.Add(p);//将要修改的对象放到数据集合中
State["person"] = null;
}
else
{
Person p = new Person() { Age = Convert.ToInt32(ConvertTo(age)), Name = name };
PersonCollection.PersonList.Add(p);//将要新增的对象放到集合中
PersonDB.Person.InsertOnSubmit(p);//新增到数据库
PersonDB.SubmitChanges();//保存数据库的改变
}
this.Name.Text = "";
this.Age.Text = "";
}
} private void BtnDelete_OnClick(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
if (button != null)
{
Person person = button.DataContext as Person;
PersonCollection.PersonList.Remove(person);
PersonDB.Person.DeleteOnSubmit(person);
PersonDB.SubmitChanges();
}
} private void BtnEdit_OnClick(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
if (button != null)
{
Person person = button.DataContext as Person;
this.Name.Text = person.Name;
this.Age.Text = person.Age.ToString();
State["person"] = person;
PersonCollection.PersonList.Remove(person);
}
}
}
MainPage.xaml代码:
<phone:PhoneApplicationPage
x:Class="WPCRUD.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True"
xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls"
>
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid x:Name="ContentPanel" Grid.Row="" Margin="12,0,12,0">
<controls:Pivot>
<controls:PivotItem Header="WPCRUD">
<ListBox Name="PersonListBox" ItemsSource="{Binding PersonList}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch" Width="">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="" />
<ColumnDefinition Width="" />
<ColumnDefinition Width="" />
<ColumnDefinition Width="" />
<ColumnDefinition Width="" />
</Grid.ColumnDefinitions>
<TextBlock
Text="{Binding Id}"
FontSize="{StaticResource PhoneFontSizeLarge}"
Grid.Column=""
VerticalAlignment="Top" Margin="0, 12, 10, 0"/>
<TextBlock
Text="{Binding Age}"
FontSize="{StaticResource PhoneFontSizeLarge}"
Grid.Column=""
VerticalAlignment="Top" Margin="0, 12, 5, 0"/>
<TextBlock
Text="{Binding Name}"
FontSize="{StaticResource PhoneFontSizeLarge}"
Grid.Column=""
VerticalAlignment="Top" Margin="0, 12, 5, 0" />
<Button BorderThickness="" Name="btnDelete" Click="BtnDelete_OnClick" Grid.Column="" Margin="-5, -18, 0, 0">
<Image
Source="Assets/appbar.delete.rest.png"
Height=""
Width=""/>
</Button>
<Button BorderThickness="" Name="btnEdit" Click="BtnEdit_OnClick" Grid.Column="" Margin="-5, -18, 0, 0">
<Image
Source="Assets/appbar.check.rest.png"
Height=""
Width=""/>
</Button>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</controls:PivotItem>
</controls:Pivot>
</Grid>
<StackPanel x:Name="AddPanel" Grid.Row="" Margin="12,0,12,0">
<TextBlock Text="姓名:"/>
<TextBox x:Name="Name"/>
<TextBlock Text="年龄:"/>
<TextBox x:Name="Age"/>
<Button Content="保存" Name="btnOk" Click="BtnOk_OnClick"></Button>
</StackPanel>
</Grid>
</phone:PhoneApplicationPage>
代码下载:WPCRUD.zip
WindowsPhone8 数据库增删改查的更多相关文章
- Yii2.0高级框架数据库增删改查的一些操作(转)
yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...
- 2. MongoDB基本操作 —— 用Mongo.exe操作数据库增删改查
一.开篇 传统的关系数据库一般由数据库(database).表(table).记录(record)三个层次概念组成,MongoDB是由数据库(database).集合(collection).文档对象 ...
- go——beego的数据库增删改查
一直都不理解使用go语言的时候,为什么还要自己去装beego,以为使用go便可以解决所有的问题,结果在朋友的点拨下,才意识到: go与beego的关系就好比是nodejs与thinkjs的关系,因此也 ...
- (转)SQLite数据库增删改查操作
原文:http://www.cnblogs.com/linjiqin/archive/2011/05/26/2059182.html SQLite数据库增删改查操作 一.使用嵌入式关系型SQLite数 ...
- Yii2.0高级框架数据库增删改查的一些操作
yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...
- MVC——数据库增删改查(Razor)——Html语法
一.显示界面 .Models(模板) private MyDBDataContext _context = new MyDBDataContext(); public List<Info> ...
- MVC——数据库增删改查(Razor)
一.显示信息 .Models(模板) private MyDBDataContext _context = new MyDBDataContext(); //定义一个变量取出所有数据 public L ...
- MVC——数据库增删改查(aspx)
MVC: V(View) :视图→就是页面的模板 C(Control): 控制器→客户主要面对的就是控制器, M(Model):模板→在模板里面主要就是写关于数据库的各种增删改查的方法 它们之间的关系 ...
- Android(java)学习笔记193:利用谷歌API对数据库增删改查(推荐使用)
接下来我们通过项目案例来介绍:这个利用谷歌API对数据库增删改查 1.首先项目图: 2.这里的布局文件activity_main.xml: <LinearLayout xmlns:android ...
随机推荐
- Adding DTrace Probes to PHP Extensions
By cj on Dec 06, 2012 The powerful DTrace tracing facility has some PHP-specific probes that can b ...
- RosettaNet
RosettaNet 这一名字源自于 1799 年在埃及发现的 Rosetta Stone .这要追溯到公元前 196 年,该石头是在 Rosetta (Rashid) 镇附近被人发现的,上面用两种不 ...
- hql & mysql 札记
最近在某D实习,刚去就开始各种写HQL,碰壁很多次. 几个知识点记录一下,逐个攻破. sql 中的case when, 选择循环的写法.(http://www.cnblogs.com/zengen/a ...
- Socket 之 同步以及异步通信
用netstat侦听下端口状态 同步通信: 预定义结构体,同步通信没有多线程异步委托回调,所以无需预定义结构体 客户端Client: class Program { static void Main( ...
- 从零开始学JAVA(01)-JAVA开发环境安装
写在前面: 本人没有JAVA基础(包括语法.开发环境),未使用开发工具开发过程序,如果有不对或误导的地方,欢迎指正. 本系列所有文章使用Eclipse,JDK是Version 7 Update 51, ...
- Phone List
Problem Description Given a list of phone numbers, determine if it is consistent in the sense that n ...
- UITableView加载显示更多内容
#import <UIKit/UIKit.h> @interface ViewController : UIViewController @end #import "ViewCo ...
- 8. Android框架和工具之 NineOldAndroids(动画框架)
1. NineOldAndroids 自Android 3.0以上的版本,SDK新增了一个android.animation包,里面的类都是跟动画效果实现相关的,通过Honeycomb API,能够实 ...
- 【Mood-12】Android开发相关书籍推荐
新年伊始,找到Android进阶干货若干,2015拜读. 1.Android应用UI设计模式 目前,谷歌Android操作系统在移动市场中风头正劲,并且未来发展势不可挡.<Android应用UI ...
- Java学习笔记——单例设计模式Singleton
单例设计模式:singleton 解决的问题: 确保程序在运行过程中,某个类的实例instance只有一份. 特点: 1 构造函数私有化 2 自己内部声明自己 3 提供一个public方法,负责实例化 ...