今天第一次在博客园发表文章,如果有的地方写的不对,还请大家指出!
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