Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > Windows Store Apps > Windows Store and External Database (C#) > Windows Store Apps and SQL Server Database Part 2 (C#)



Clound SSD Virtual Server

Windows Store Apps and SQL Server Database Part 2 (C#)

Windows Store Apps and SQL Server Database Part 2 (C#) หัวข้อนี้จะเป็น Part ต่อจากบทความก่อนหน้านี้ เกี่ยวกับ Windows Store Apps กับ SQL Server Database โดยเราจะมาประยุกต์การเขียน Windows Store Apps เพื่อทำการ Insert / Update/ Delete ข้อมูลที่อยู่บน SQL Server ผ่านช่องทาง Web Services และสำหรับวิธีการนั้น บน Web Services จะต้องทำการออกแบบ Method สำหรับรับค่า Parameters ที่จะส่งมาจาก Windows Store Apps จากนั้นเมื่อได้ค่า Paramters ต่าง ๆ แล้ว Web Services จะคอยทำหน้าที่นำค่าที่ได้ไป Insert ลงใน SQL Server

Windows Store Apps and SQL Server Database Part 2 (C#)

Windows Store Apps and SQL Server Database


Windows Store Apps and SQL Server Database Part 1 (C#)


ขั้นตอนที่ 1 การออกแบบ Web Services กับ SQL Server Database

Windows Store Apps and SQL Server Database Part 2 (C#)

CREATE TABLE [dbo].[customer](
	[CustomerID] [varchar](4) NOT NULL,
	[Name] [varchar](50) NULL,
	[Email] [varchar](50) NULL,
	[CountryCode] [varchar](2) NULL,
	[Budget] [float] NULL,
	[Used] [float] NULL,
 CONSTRAINT [PK_customer] PRIMARY KEY CLUSTERED 
(
	[CustomerID] ASC
))

INSERT INTO [customer] VALUES ('C001', 'Win Weerachai', '[email protected]', 'TH', 1000000, 600000)
INSERT INTO [customer] VALUES ('C002', 'John Smith', '[email protected]', 'UK', 2000000, 800000)
INSERT INTO [customer] VALUES ('C003', 'Jame Born', '[email protected]', 'US', 3000000, 600000)
INSERT INTO [customer] VALUES ('C004', 'Chalee Angel', '[email protected]', 'US', 4000000, 100000)

โครงสร้าง Table บน SQL Server

ออกแบบ Method บน Web Services ที่ทำหน้าที่รับค่า Parameters
        public string AddData(string sCustomerID,
            string sName,
            string sEmail,
            string sCountryCode,
            string sBudget,
            string sUsed)
        {

        }

การ Insert ข้อมูลลงใน Table ของ SQL Server
                strSQL = "INSERT INTO customer (CustomerID,Name,Email,CountryCode,Budget,Used) VALUES " +
                " ('" + sCustomerID + "' " +
                " ,'" + sName + "' " +
                " ,'" + sEmail + "' " +
                " ,'" + sCountryCode + "' " +
                " ,'" + sBudget + "' " +
                " ,'" + sUsed + "') ";









Code ทั้งหมด
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

using System.Data;
using Newtonsoft.Json;
using System.Data.SqlClient;

namespace myAppWeb
{
    /// <summary>
    /// Summary description for myWSV
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class myWSV : System.Web.Services.WebService
    {


        [WebMethod]
        public string AddData(string sCustomerID,
            string sName,
            string sEmail,
            string sCountryCode,
            string sBudget,
            string sUsed)
        {

            try
            {
                SqlConnection objConn = new SqlConnection();
                SqlCommand objCmd = new SqlCommand();

                String strConnString, strSQL;

                strConnString = "Server=localhost;UID=sa;PASSWORD=mypassword;Database=mydatabase;Max Pool Size=400;Connect Timeout=600;";

                objConn.ConnectionString = strConnString;
                objConn.Open();

                strSQL = "INSERT INTO customer (CustomerID,Name,Email,CountryCode,Budget,Used) VALUES " +
                " ('" + sCustomerID + "' " +
                " ,'" + sName + "' " +
                " ,'" + sEmail + "' " +
                " ,'" + sCountryCode + "' " +
                " ,'" + sBudget + "' " +
                " ,'" + sUsed + "') ";

                objCmd = new SqlCommand();
                objCmd.Connection = objConn;
                objCmd.CommandText = strSQL;
                objCmd.CommandType = CommandType.Text;
                objCmd.ExecuteNonQuery();

                return "1"; // return sccess.

            }
            catch (Exception ex)
            {
                return "0"; // return failed.
            }
        }


    }
}


ขั้นตอนที่ 2 บน Windows Store เรียกใช้งาน Web Services และส่งค่า Parameters ไปที่ Web Services

            var client = new myWebServices.myWSVSoapClient();
            var result = await client.AddDataAsync(this.txtCustomerID.Text,
                this.txtName.Text,
                this.txtEmail.Text,
                this.txtCountryCode.Text,
                this.txtBudget.Text,
                this.txtUsed.Text);


Windows Store Apps and SQL Server Database Part 2 (C#)

กรณีที่ทำการ Add Services จาก Web Services อยู่แล้ว สามารถคลิก Update เพื่อทำการ Update Method ใหม่ ๆ


MainPage.xaml

Windows Store Apps and SQL Server Database Part 2 (C#)

ออกแบบ Form สำหรับ Input ข้อมูล

<Page
    x:Class="WindowsStoreApps.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:WindowsStoreApps"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

        <TextBlock HorizontalAlignment="Left" Margin="524,57,0,0" TextWrapping="Wrap" Text="Add Data" VerticalAlignment="Top" FontSize="25"/>
        <TextBlock HorizontalAlignment="Left" Margin="364,115,0,0" TextWrapping="Wrap" Text="CustomerID :" VerticalAlignment="Top" FontSize="20"/>
        <TextBox x:Name="txtCustomerID" HorizontalAlignment="Left" Height="36" Margin="669,116,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="326" FontSize="20" FontFamily="Global User Interface"/>
        <TextBlock HorizontalAlignment="Left" Margin="362,182,0,0" TextWrapping="Wrap" Text="Name : " VerticalAlignment="Top" FontSize="20"/>
        <TextBox x:Name="txtName" HorizontalAlignment="Left" Height="36" Margin="667,176,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="319" FontSize="20" FontFamily="Global User Interface"/>
        <TextBlock HorizontalAlignment="Left" Margin="362,237,0,0" TextWrapping="Wrap" Text="Email : " VerticalAlignment="Top" FontSize="20"/>
        <TextBox x:Name="txtEmail" HorizontalAlignment="Left" Height="36" Margin="667,235,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="326" FontSize="20" FontFamily="Global User Interface"/>

        <TextBlock HorizontalAlignment="Left" Margin="362,303,0,0" TextWrapping="Wrap" Text="Country : " VerticalAlignment="Top" FontSize="20"/>
        <TextBox x:Name="txtCountryCode" HorizontalAlignment="Left" Height="36" Margin="667,299,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="326" FontSize="20" FontFamily="Global User Interface"/>
        <TextBlock HorizontalAlignment="Left" Margin="362,369,0,0" TextWrapping="Wrap" Text="Budget :" VerticalAlignment="Top" FontSize="20"/>
        <TextBox x:Name="txtBudget" HorizontalAlignment="Left" Height="36" Margin="667,365,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="326" FontSize="20" FontFamily="Global User Interface"/>
        <TextBlock HorizontalAlignment="Left" Margin="364,433,0,0" TextWrapping="Wrap" Text="Used : " VerticalAlignment="Top" FontSize="20"/>
        <TextBox x:Name="txtUsed" HorizontalAlignment="Left" Height="36" Margin="669,434,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="326" FontSize="20" FontFamily="Global User Interface"/>
        <Button x:Name="btnSave" Content="Save" HorizontalAlignment="Left" Margin="554,522,0,0" VerticalAlignment="Top" FontSize="20" Width="120" FontFamily="Global User Interface" Click="btnSave_Click"/>

    </Grid>

</Page>


MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Devices.Geolocation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
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;

using WindowsStoreApps.myWebServices;
using Windows.UI.Popups;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace WindowsStoreApps
{
    /// <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 MainPage()
        {
            this.InitializeComponent();
        }

        private async void btnSave_Click(object sender, RoutedEventArgs e)
        {

            var client = new myWebServices.myWSVSoapClient();
            var result = await client.AddDataAsync(this.txtCustomerID.Text,
                this.txtName.Text,
                this.txtEmail.Text,
                this.txtCountryCode.Text,
                this.txtBudget.Text,
                this.txtUsed.Text);

            string jsonData = result.Body.AddDataResult;

            if (jsonData == "0")
            {
                MessageDialog msgDialog = new MessageDialog("Add Data Failed", "Error");
                await msgDialog.ShowAsync();
            }
            else
            {
                MessageDialog msgDialog = new MessageDialog("Add Data Success.", "Success");
                await msgDialog.ShowAsync();
            }

        }

    }

}

Result

Windows Store Apps and SQL Server Database Part 2 (C#)

ทดสอบการทำงาน

Windows Store Apps and SQL Server Database Part 2 (C#)

ทดสอบการเพิ่มข้อมูล

Windows Store Apps and SQL Server Database Part 2 (C#)

แสดง Message ในกรณีที่ทำการเพิ่มข้อมูลเรียบร้อยแล้ว

Windows Store Apps and SQL Server Database Part 2 (C#)

เมื่อกลับไปดูที่ Table บน SQL Server จะเห็นว่ามีข้อมูลถูก Insert ลงใน Record








ตัวอย่างการ Update ข้อมูล

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

using System.Data;
using Newtonsoft.Json;
using System.Data.SqlClient;

namespace myAppWeb
{
    /// <summary>
    /// Summary description for myWSV
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class myWSV : System.Web.Services.WebService
    {

        [WebMethod]
        public void UpdateData(string sCustomerID,
            string sName,
            string sEmail,
            string sCountryCode,
            string sBudget,
            string sUsed)
        {

            SqlConnection objConn = new SqlConnection();
            SqlCommand objCmd = new SqlCommand();

            String strConnString, strSQL;

            strConnString = "Server=localhost;UID=sa;PASSWORD=mypassword;Database=mydatabase;Max Pool Size=400;Connect Timeout=600;";

            objConn.ConnectionString = strConnString;
            objConn.Open();

            strSQL = "UPDATE customer SET " +
            " Name = '" + sName + "' " +
            " ,Email = '" + sEmail + "' " +
            " ,CountryCode = '" + sCountryCode + "' " +
            " ,Budget = '" + sBudget + "' " +
            " ,Used = '" + sUsed + "' " +
            " WHERE CustomerID = '" + sCustomerID + "' ";

            objCmd = new SqlCommand();
            objCmd.Connection = objConn;
            objCmd.CommandText = strSQL;
            objCmd.CommandType = CommandType.Text;
            objCmd.ExecuteNonQuery();
        }

    }
}

        private async void btnSave_Click(object sender, RoutedEventArgs e)
        {
            var client = new myWebServices.myWSVSoapClient();
            var result = await client.UpdateDataAsync(this.lblCustomerID.Text,
                this.txtName.Text,
                this.txtEmail.Text,
                this.txtCountryCode.Text,
                this.txtBudget.Text,
                this.txtUsed.Text);

            this.Frame.Navigate(typeof(MainPage));
        }



ตัวอย่างการ Delete ข้อมูล

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

using System.Data;
using Newtonsoft.Json;
using System.Data.SqlClient;

namespace myAppWeb
{
    /// <summary>
    /// Summary description for myWSV
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class myWSV : System.Web.Services.WebService
    {

        [WebMethod]
        public void DeleteData(string sCustomerID)
        {

            SqlConnection objConn = new SqlConnection();
            SqlCommand objCmd = new SqlCommand();

            String strConnString, strSQL;

            strConnString = "Server=localhost;UID=sa;PASSWORD=mypassword;Database=mydatabase;Max Pool Size=400;Connect Timeout=600;";
            strSQL = "DELETE FROM customer WHERE CustomerID ='" + sCustomerID + "'";

            objConn.ConnectionString = strConnString;
            objConn.Open();

            objCmd = new SqlCommand();
            objCmd.Connection = objConn;
            objCmd.CommandText = strSQL;
            objCmd.CommandType = CommandType.Text;
            objCmd.ExecuteNonQuery();

        }

    }
}

        private async void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            string CustomerID = "C001";

            var client = new myWebServices.myWSVSoapClient();
            var result = await client.DeleteDataAsync(CustomerID);
        }



.

   
Share


ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2014-06-28 16:09:45 / 2017-03-19 15:10:28
  Download : No files
 Sponsored Links / Related

 
Windows Store Apps and SQL Server Database Part 1 (C#)
Rating :

 
Windows Store Apps and MS Access Database (C#)
Rating :

 
Windows Store Apps and MySQL Database (C#)
Rating :

 
Windows Store Apps and Oracle Database (C#)
Rating :

 
Windows Store Apps and SQL Azure Database (C# , Windows Azure)
Rating :


ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 04
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่