今天第一次在博客园发表文章,如果有的地方写的不对,还请大家指出!

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 数据库增删改查的更多相关文章

  1. Yii2.0高级框架数据库增删改查的一些操作(转)

    yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...

  2. 2. MongoDB基本操作 —— 用Mongo.exe操作数据库增删改查

    一.开篇 传统的关系数据库一般由数据库(database).表(table).记录(record)三个层次概念组成,MongoDB是由数据库(database).集合(collection).文档对象 ...

  3. go——beego的数据库增删改查

    一直都不理解使用go语言的时候,为什么还要自己去装beego,以为使用go便可以解决所有的问题,结果在朋友的点拨下,才意识到: go与beego的关系就好比是nodejs与thinkjs的关系,因此也 ...

  4. (转)SQLite数据库增删改查操作

    原文:http://www.cnblogs.com/linjiqin/archive/2011/05/26/2059182.html SQLite数据库增删改查操作 一.使用嵌入式关系型SQLite数 ...

  5. Yii2.0高级框架数据库增删改查的一些操作

    yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...

  6. MVC——数据库增删改查(Razor)——Html语法

    一.显示界面 .Models(模板) private MyDBDataContext _context = new MyDBDataContext(); public List<Info> ...

  7. MVC——数据库增删改查(Razor)

    一.显示信息 .Models(模板) private MyDBDataContext _context = new MyDBDataContext(); //定义一个变量取出所有数据 public L ...

  8. MVC——数据库增删改查(aspx)

    MVC: V(View) :视图→就是页面的模板 C(Control): 控制器→客户主要面对的就是控制器, M(Model):模板→在模板里面主要就是写关于数据库的各种增删改查的方法 它们之间的关系 ...

  9. Android(java)学习笔记193:利用谷歌API对数据库增删改查(推荐使用)

    接下来我们通过项目案例来介绍:这个利用谷歌API对数据库增删改查 1.首先项目图: 2.这里的布局文件activity_main.xml: <LinearLayout xmlns:android ...

随机推荐

  1. C#对Windows服务的操作

    一.安装服务: private void InstallService(IDictionary stateSaver, string filepath) { try { System.ServiceP ...

  2. Golang学习 - io/ioutil 包

    ------------------------------------------------------------ // Discard 是一个 io.Writer 接口,调用它的 Write ...

  3. nie题目-游戏排行榜设计

    一个mmorpg游戏,玩家众多,需要对玩家战斗力进行排行,并且战斗力变化时需要及时刷新.需要设计一个这样的排行榜. 关于海量数据排行榜的做法,云风在他的博客里给过思路,谈谈陌陌争霸在数据库方面踩过的坑 ...

  4. Linux进程管理之task_struct结构

    转载:http://blog.csdn.net/npy_lp/article/details/7335187 内核源码:linux-2.6.38.8.tar.bz2 目标平台:ARM体系结构 进程是处 ...

  5. Linux高级字符设备驱动

    转载:http://www.linuxidc.com/Linux/2012-05/60469p4.htm 1.什么是Poll方法,功能是什么? 2.Select系统调用(功能)      Select ...

  6. 小小的封装了一个pie的echarts

    function showData(ele,arr1,arr2){ var myChart2 = echarts.init(document.getElementById(ele)); var opt ...

  7. 【阿里云产品公测】PTS测试 SLB+ECS+RDS组合的DZ论坛负载极限压力,100并发2000页

    作者:阿里云用户woaj01 ​​环境介绍: 1.ECS:1核 1G 5M 杭州 2.RDS:240M  5G  杭州内网 3.SLB:私网实例​ 配置测试环境: 测试脚本: 1.生成参数文件,我的方 ...

  8. Windows8不联网直接安装.Net 3.5 Framework的方法

    把你的系统ISO加载到虚拟光驱或插入系统安装盘,找到X:\sources\sxs路径(X是你的光驱盘符).输入下面命令,盘符以D盘为例DISM /Online /Enable-Feature /Fea ...

  9. ionic实现双击返回键退出软件

    1.首先要安装cordova插件:插件地址:cordova plugin add https://github.com/EddyVerbruggen/Toast-PhoneGap-Plugin.git ...

  10. IT技术方案最佳实践方案的收集

    一.图片鉴别服务 1. 阿里云,腾讯云等公开的服务. 2. 图谱科技提供的API 二. 网络直播服务器 1. SRS2 开源服务器 (https://github.com/ossrs/srs/wiki ...