ตอนที่ 15 : Show Case 3 : Update Data (WP and Mobile Services) |
ตอนที่ 15 : Show Case 3 : Update Data (WP and Mobile Services) บทความการเขียน Windows Phone เพื่อทำการ Update หรือแก้ไขข้อมูลในตารางของ Mobile Services ที่อยู่บน Windows Azure โดยในตัวอย่างนี้จะออกแบบ Page เป็น 2 Form ด้วยกัน คือ Page แรกใช้ LongListSelector แสดงรายการข้อมูลทั้งหมด ส่วน Page ที่สองสำหรับแสดงข้อมูลที่ได้เลือก เพื่อทำการแสดงช่อง Textbox ไว้สำหรับแก้ไขข้อมูล
Windows Phone Mobile Services Update Form
Windows Phone Mobile Services Update Form
สำหรับขั้นตอนนั้นก็คือสร้าง Page แรกด้วย LongListSelector จากนั้นดึงข้อมูลมาจาก Mobile Services และแต่ล่ะ Item สามารถที่จะเลือกรายการเพื่อ Update ด้วยการส่งค่า id ไปยัง Page ที่สอง ใน Page นี้จะมีหน้าที่ไปดึงพวกรายละเอียดต่าง ๆ มาแสดงใน Textbox เพื่อรอทำการแก้ไข Update ข้อมูล
Example ตัวอย่างการทำระบบแก้ไข Update Data ที่อยู่บน Mobile Services ด้วย Windows Phone

ตอนนี้เรามี Mobile Service อยู่ 1 รายการ

ชื่อตารางว่า MyMember

มีข้อมูลอยู่ทั้งหมด 3 รายการ

กลับมายัง Project ของ Windows Phone บน Visual Studio

โครงสร้างไฟล์

ในไฟล์ App.xaml.cs ให้ Copy Url และ key มาวางดังรูป จากนั้นออกแบบ Layout และเขียน Code ดังนี้

ไฟล์ชุดแรกจะเป็น MainPage.xaml และ MainPage.xaml.cs สำหรับหน้า แสดงข้อมูลใน Listbox
MainPage.xaml

<phone:PhoneApplicationPage
x:Class="myPhoneApp.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">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="ThaiCrate.Com" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" FontSize="45"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<phone:LongListSelector Grid.Row="4" Grid.ColumnSpan="2" Name="myListItems" SelectionChanged="myListItems_SelectionChanged">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Username}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" Margin="5,0,0,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Text="{Binding Tel}" TextWrapping="Wrap" Margin="5,0,0,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Text="{Binding Email}" TextWrapping="Wrap" Margin="5,0,0,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using myPhoneApp.Resources;
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json;
namespace myPhoneApp
{
public class MyMember
{
public int Id { get; set; }
[JsonProperty(PropertyName = "username")]
public string Username { get; set; }
[JsonProperty(PropertyName = "password")]
public string Password { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "tel")]
public string Tel { get; set; }
[JsonProperty(PropertyName = "email")]
public string Email { get; set; }
}
public partial class MainPage : PhoneApplicationPage
{
private MobileServiceCollection<MyMember, MyMember> items;
private IMobileServiceTable<MyMember> memberTable = App.MobileService.GetTable<MyMember>();
// Constructor
public MainPage()
{
InitializeComponent();
}
private async void RefreshMemberItems()
{
try
{
items = await memberTable.ToCollectionAsync();
}
catch (MobileServiceInvalidOperationException e)
{
MessageBox.Show(e.Message, "Error loading items", MessageBoxButton.OK);
}
myListItems.ItemsSource = items;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
RefreshMemberItems();
}
private void myListItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MyMember member = (sender as LongListSelector).SelectedItem as MyMember;
NavigationService.Navigate(new Uri("/UpdatePage.xaml?sid=" + member.Id.ToString(), UriKind.Relative));
}
}
}
เพิ่ม Page ขึ้นมาอีก 1 ชุด สำหรับหน้า Update Page

คลิกขวาที่ Solution -> Add -> New Item... เลือก Windows Phone Page แบบแนวตั้ง ชื่อเป็น UpdatePage.xaml

ได้ไฟล์ UpdatePage.xaml และ UpdatePage.xaml.cs
UpdatePage.xaml

<phone:PhoneApplicationPage
x:Class="myPhoneApp.UpdatePage"
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"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="ThaiCrate.Com" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" FontSize="45"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock HorizontalAlignment="Left" Margin="10,8,0,0" TextWrapping="Wrap" Text="Update Form" VerticalAlignment="Top" FontSize="36"/>
<TextBlock HorizontalAlignment="Left" Margin="10,71,0,0" TextWrapping="Wrap" Text="Username :" VerticalAlignment="Top"/>
<TextBox x:Name="txtUsername" HorizontalAlignment="Left" Height="72" Margin="130,50,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="234"/>
<TextBlock HorizontalAlignment="Left" Margin="10,142,0,0" TextWrapping="Wrap" Text="Password :" VerticalAlignment="Top"/>
<PasswordBox x:Name="txtPassword" HorizontalAlignment="Left" Margin="130,122,0,0" VerticalAlignment="Top" Width="194"/>
<TextBlock HorizontalAlignment="Left" Margin="10,210,0,0" TextWrapping="Wrap" Text="Name :" VerticalAlignment="Top"/>
<TextBox x:Name="txtName" HorizontalAlignment="Left" Height="72" Margin="130,181,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="284"/>
<TextBlock HorizontalAlignment="Left" Margin="10,280,0,0" TextWrapping="Wrap" Text="Email :" VerticalAlignment="Top"/>
<TextBox x:Name="txtEmail" HorizontalAlignment="Left" Height="72" Margin="130,253,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="326"/>
<TextBlock HorizontalAlignment="Left" Margin="10,355,0,0" TextWrapping="Wrap" Text="Tel :" VerticalAlignment="Top"/>
<TextBox x:Name="txtTel" HorizontalAlignment="Left" Height="72" Margin="130,330,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="234"/>
<Button x:Name="btnSave" Content="Save" HorizontalAlignment="Left" Margin="167,429,0,0" VerticalAlignment="Top" Click="btnSave_Click"/>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
UpdatePage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json;
namespace myPhoneApp
{
public partial class UpdatePage : PhoneApplicationPage
{
private MobileServiceCollection<MyMember, MyMember> items;
private IMobileServiceTable<MyMember> memberTable = App.MobileService.GetTable<MyMember>();
private String id = "";
public UpdatePage()
{
InitializeComponent();
}
private async void InfoMember()
{
try
{
NavigationContext.QueryString.TryGetValue("sid", out id);
items = await memberTable
.Where(memberItem => memberItem.Id == Convert.ToInt32(id))
.ToCollectionAsync();
if (items.Count > 0)
{
MyMember member = items[0];
txtUsername.Text = member.Username.ToString();
txtPassword.Password = member.Password.ToString();
txtName.Text = member.Name.ToString();
txtEmail.Text = member.Email.ToString();
txtTel.Text = member.Tel.ToString();
}
else
{
MessageBox.Show("Not found Data!");
}
}
catch (MobileServiceInvalidOperationException ex)
{
MessageBox.Show("Error : " + ex.Message);
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
InfoMember();
}
private async void btnSave_Click(object sender, RoutedEventArgs e)
{
try
{
//** Get Item for Update ***/
items = await memberTable
.Where(memberItem => memberItem.Id == Convert.ToInt32(id))
.ToCollectionAsync();
MyMember member = items[0];
member.Name = txtName.Text;
member.Password = txtPassword.Password;
member.Name = txtName.Text;
member.Email = txtEmail.Text;
member.Tel = txtTel.Text;
//*** Update Record ***/
await memberTable.UpdateAsync(member);
MessageBox.Show("Update Data Successfully.");
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
catch (MobileServiceInvalidOperationException ex)
{
MessageBox.Show("Error : " + ex.Message);
}
}
}
}
Screenshot

หน้าแสดงรายการข้อมูลทั้งหมดที่มาจาก Mobile Services ให้คลิกเพื่อเลือกทำการแก้ไขข้อมูล

แสดง Page สำหรับการแก้ไขข้อมูล

ทดสอบการแก้ไขข้อมูล และ Update ข้อมูลไปยัง Mobile Services

ผลการ Update ข้อมูล

ในหน้า LongListSelector ข้อมูลถูก Update เรียบร้อยแล้ว

เมื่อกลับไปยัง Mobile Services ที่อยู่บน Windows Azure ข้อมูลก็จะถูก Update เรียบร้อย
สามารถทำการดาวน์โหลด Code ทั้งหมดได้จากท้ายบทความ
บทความถัดไปที่แนะนำให้อ่าน
บทความที่เกี่ยวข้อง
|