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 Storage / Data (C#) > Windows Store Apps DataBinding - ListBox / Database Binding (C#)



Clound SSD Virtual Server

Windows Store Apps DataBinding - ListBox / Database Binding (C#)

Windows Store Apps DataBinding - ListBox / Database Binding (C#) สำหรับ ListBox บน Windows Store Apps จะมีรูปแบบการทำงานและรูปแบบการเขียนเหมือนกับ Windows Form Application คือ ListBox เป็นรูปแบบการนำเสนอรายการที่สามารถมีได้มากกว่า 1 รายการ (Columns) และประกอบด้วยหลาย ๆ Item (Rows) และมีคุณสมบัติการปรับแต่งแต่ล่ะ Column / Row ก็สามารถกำหนดคุณสมบัติอื่น ๆ ได้อีกมากมาย เช่น ผู้ใช้สามารถเลือกรายการบน ListBox ได้หลาย Item หรือจะกำหนดพวกความกว้าง และ ความสูงของแต่ล่ะ Item ก็สามารถปรับแต่งได้ตามความต้องการ หรือจะเป็นการสร้าง และแทรก Control ย่อยในแต่ล่ะ Item ของ ListBox ก็สามารถทำได้เช่นเดียวกัน

ปกติแล้วการสร้าง ListBox สามารถสร้าง Item ต่าง ๆ ได้บน XAML ได้ทันที เช่น

<ListBox x:Name="lsBox"
    <x:String>Item 1</x:String>
    <x:String>Item 2</x:String>
    <x:String>Item 3</x:String>
</ListBox> 

จาก Tag นี้แสดงว่า ListBox ประกอบด้วย 3 Item คือ Item 1 , Item 2 และ Item 3

แต่จะเห็นว่า Code นี้ถูกเขียนไว้บนหน้าจอ XAML ไม่สามารถเพิ่มหรือแก้ไขรายการ Item ต่าง ๆ ได้ ฉะนั้นการทำ DataBinding จึงมีความจำเป็นในการที่จะสร้าง Dynamic Data ให้แสดงข้อมูลหรือรับข้อมูลจากแหล่งต่าง ๆ ได้ มาลองดูตัวอย่างการทำ DataBinding บน ListBox แบบง่าย ๆ

ซึ่งก่อนที่จะทำ DataBinding นั้น เราจะต้องมีแหล่ง Data Source หรือแหล่งที่มาของข้อมูลซะก่อน โดยข้อมูล อาจจะมาจากภายใน Application เอง เช่น การ Input ข้อมูล การอ่านข้อมูลมาจาก Local หรือจากภายนอก เช่น Database หรือผ่าน API ต่าง ๆ และอย่างที่เราทราบกันอยู่แล้วว่า Windows Store Apps จะไม่มีในส่วนของ ADO.NET และ System.Data ที่จะจัดการกับ DataSource ผ่าน DataSet หรือ DataTable แต่เรายังคงจะสามารถใช้ Collection หลาย ๆ ตัวที่สร้างชุดของ DataSource ได้ ซึ่งใน API ของ WinRT ก็มีอยู่หลายวิธี แต่วิธีที่ง่ายและได้รับความนิยมมาก คือการสร้าง Model ของ Class และ Mapping Data กับ List ซึ่งจะมีความยึดหยุ่นกับการเก็บข้อมูลได้หลากหลายรูปแบบ เก็บข้อมูลได้ทั้งแบบ Single Row และ Multi Rows ขึ้นอยู่กับ Model ที่ถูกออกแบบไว้ เช่น

    public class MyMember
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }

เป็นการสร้าง Class Model ชื่อว่า MyMember ประกอบด้วย Property ต่าง ๆ คือ Id, Name และ Email

            List<MyMember> items = new List<MyMember>();

            items.Add(new MyMember { Id = 1, Name = "Win", Email = "[email protected]" });

สร้าง List ที่เก็บ Model ของ MyMember ซึ่งตอนนี้เราจะได้ List ที่เป็น Object ของ Class MyMember ที่ประกอบด้วย Id, Name และ Email และเมื่อได้ List นี้แล้ว สามารถนำไปเป็น Data Source ให้กับ Control ต่าง ๆ ได้ทันที








Example 1 ตัวอย่างการสร้าง ListBox และ Binding ข้อมูลจาก List แบบง่าย ๆ

Windows Store Apps DataBinding - ListBox

สร้าง Control ของ ListBox และเพิ่มในส่วนของ DataTemplate ดังนี้

        <ListBox x:Name="myListBox" HorizontalAlignment="Left" Height="274" Margin="58,98,0,0" VerticalAlignment="Top" Width="670">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Margin="0,0,0,17">
                        <StackPanel Width="50">
                            <TextBlock Text="{Binding Id}" TextWrapping="Wrap" FontSize="35" Foreground="#FFBFB9B9" Margin="5,0,0,0"/>
                        </StackPanel>
                        <StackPanel Width="150">
                            <TextBlock Text="{Binding Name}" TextWrapping="Wrap" FontSize="35" Foreground="#FFBFB9B9" Margin="5,0,0,0"/>
                        </StackPanel>
                        <StackPanel Width="400">
                            <TextBlock Text="{Binding Email}" TextWrapping="Wrap" FontSize="35" Foreground="#FFBFB9B9" Margin="5,0,0,0"/>
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

ซึ่งประกอบด้วย Column ชื่อว่า Id, Name และ Email โดยทำการเชื่อมโยงข้อมูลไว้พร้อมแล้ว เช่น Text="{Binding Email}" หมายถึง Binding กับข้อมูลของ Email

ขั้นตอนถัดไปคือการสร้าง Class Model เพื่อของตัวแปรเพื่อจะเชื่อม mapping data และเก็บค่าของ ข้อมูล Id, Name และ Email ในรูปแบบของ List

    public class MyMember
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }

จากนั้นก็สร้าง List โดยอ้างอิง Object ของ Class ชื่อ MyMember ที่เราได้สร้างไว้ก่อนหน้านี้ ซึ่งจะมี Property ที่เก็บ Id, Name และ Email

            List<MyMember> items = new List<MyMember>();

            items.Add(new MyMember { Id = 1, Name = "Win", Email = "[email protected]" });
            items.Add(new MyMember { Id = 2, Name = "Chai", Email = "[email protected]" });
            items.Add(new MyMember { Id = 3, Name = "Sorn", Email = "[email protected]" });
            items.Add(new MyMember { Id = 4, Name = "Keng", Email = "[email protected]" });

ตอนนี้เราได้ Object ของ List ที่ประกอบด้วย Item ต่าง ๆ ที่เก็บ Id, Name และ Email

this.myListBox.ItemsSource = items;

กำหนด ItemsSource ให้กับ ListBox

ลองมาดู Code ทั้งหมด

MainPage.xaml
<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}">
        
        <ListBox x:Name="myListBox" HorizontalAlignment="Left" Height="274" Margin="58,98,0,0" VerticalAlignment="Top" Width="670">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Margin="0,0,0,17">
                        <StackPanel Width="50">
                            <TextBlock Text="{Binding Id}" TextWrapping="Wrap" FontSize="35" Foreground="#FFBFB9B9" Margin="5,0,0,0"/>
                        </StackPanel>
                        <StackPanel Width="150">
                            <TextBlock Text="{Binding Name}" TextWrapping="Wrap" FontSize="35" Foreground="#FFBFB9B9" Margin="5,0,0,0"/>
                        </StackPanel>
                        <StackPanel Width="400">
                            <TextBlock Text="{Binding Email}" TextWrapping="Wrap" FontSize="35" Foreground="#FFBFB9B9" Margin="5,0,0,0"/>
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </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 MySql.Data.MySqlClient;

// 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 class MyMember
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            List<MyMember> items = new List<MyMember>();

            items.Add(new MyMember { Id = 1, Name = "Win", Email = "[email protected]" });
            items.Add(new MyMember { Id = 2, Name = "Chai", Email = "[email protected]" });
            items.Add(new MyMember { Id = 3, Name = "Sorn", Email = "[email protected]" });
            items.Add(new MyMember { Id = 4, Name = "Keng", Email = "[email protected]" });

            this.myListBox.ItemsSource = items;
        }
       
    }
}

Screenshot

Windows Store Apps DataBinding - ListBox

แสดงการ Binding ข้อมูลและแสดงบน Control ของ ListBox บน Windows Store Apps


Example 2 ตัวอย่างการสร้าง ListBox และ Binding ข้อมูลจาก MySql Database แบบง่าย ๆ

MySQL ตอนที่ 1 : Windows Store Apps ติดต่อกับ MySQL Database (C#)


Windows Store Apps DataBinding - ListBox

โครงสร้าง Table และ Data
CREATE TABLE `member` (
  `ID` int(2) NOT NULL auto_increment,
  `Name` varchar(50) NOT NULL,
  `Email` varchar(150) NOT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;


INSERT INTO `member` VALUES (1, 'Win', '[email protected]');
INSERT INTO `member` VALUES (2, 'Chai', '[email protected]');
INSERT INTO `member` VALUES (3, 'Sorn', '[email protected]');
INSERT INTO `member` VALUES (4, 'Keng', '[email protected]');


Windows Store Apps DataBinding - ListBox

บน Project ให้ทำการ Add Reference ของ MySql.Data.RT.dll ให้เรียบร้อย

รูปแบบการ Mapping Model กับ MySql Database

    public class MyMember
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }

สร้าง Model สำหรับ Mapping กับตัว Result จาก MySQL

            List<MyMember> items = new List<MyMember>();

            string strConnection = "server=localhost;database=mydatabase;uid=root;password=root;";

            using (MySqlConnection connection = new MySqlConnection(strConnection))
            {
                connection.Open();

                MySqlCommand cmd = new MySqlCommand("SELECT * FROM member", connection);
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        items.Add(new MyMember { Id = Convert.ToInt32(reader.GetString("ID"))
                            , Name = reader.GetString("Name")
                            , Email = reader.GetString("Email") });
                    }
                }

            }

Model Mapping กับ List ซึ่งดึง Result มาจาก MySQL Database








ลองมาดู Code ทั้งหมด

MainPage.xaml
<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}">
        
        <ListBox x:Name="myListBox" HorizontalAlignment="Left" Height="274" Margin="58,98,0,0" VerticalAlignment="Top" Width="670">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Margin="0,0,0,17">
                        <StackPanel Width="50">
                            <TextBlock Text="{Binding Id}" TextWrapping="Wrap" FontSize="35" Foreground="#FFBFB9B9" Margin="5,0,0,0"/>
                        </StackPanel>
                        <StackPanel Width="150">
                            <TextBlock Text="{Binding Name}" TextWrapping="Wrap" FontSize="35" Foreground="#FFBFB9B9" Margin="5,0,0,0"/>
                        </StackPanel>
                        <StackPanel Width="400">
                            <TextBlock Text="{Binding Email}" TextWrapping="Wrap" FontSize="35" Foreground="#FFBFB9B9" Margin="5,0,0,0"/>
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </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 MySql.Data.MySqlClient;

// 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 class MyMember
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            List<MyMember> items = new List<MyMember>();

            string strConnection = "server=localhost;database=mydatabase;uid=root;password=root;";

            using (MySqlConnection connection = new MySqlConnection(strConnection))
            {
                connection.Open();

                MySqlCommand cmd = new MySqlCommand("SELECT * FROM member", connection);
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        items.Add(new MyMember
                        {
                            Id = Convert.ToInt32(reader.GetString("ID"))
                            ,
                            Name = reader.GetString("Name")
                            ,
                            Email = reader.GetString("Email")
                        });
                    }
                }

            }

            this.myListBox.ItemsSource = items;
        }
       
    }
}

Screenshot

Windows Store Apps DataBinding - ListBox

แสดง Result ของ DataBinding บน ListBox ที่ดึง DataSource มาจาก MySQL Database


.

   
Share


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


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


   


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

 
Local app data จัดเก็บไฟล์ลง Storage บน Windows Store Apps (C#)
Rating :

 
Roaming app data จัดเก็บไฟล์ลง Storage บน Windows Store Apps (C#)
Rating :

 
Temporary app data จัดเก็บไฟล์ลง Storage บน Windows Store Apps (C#)
Rating :

 
File Dialog และ Save จัดเก็บไฟล์ลง Storage ของ Windows Store Apps (C#)
Rating :

 
Copy ไฟล์ลง Storage แสดงชื่อไฟล์ใน Storage บน Windows Store Apps (C#)
Rating :

 
ดาวน์โหลดจัดเก็บไฟล์ลงบน Storage ของ Windows Store Apps (C#)
Rating :

 
การสร้าง Text file และการจัดเก็บบน Storage ของ Windows Store Apps (C#)
Rating :

 
MySQL ตอนที่ 1 : Windows Store Apps ติดต่อกับ MySQL Database (C#)
Rating :

 
MySQL ตอนที่ 2 : Windows Store Apps ทำการ Insert , Update , Delete (C#)
Rating :

 
MySQL ตอนที่ 3 : Windows Store Apps กับ MySQL ข้าม Host หรือ Server (C#)
Rating :

 
Windows Store Apps DataBinding - ListView / Database Binding (C#)
Rating :

 
Windows Store Apps Databinding - Retrieve Data Master and Detail (C#)
Rating :

 
Windows Store Apps DataBinding - GridView / Database Binding (C#)
Rating :

 
SQLite : Windows Store Apps ติดต่อกลับ SQLite Database (C#)
Rating :

 
Windows Store Apps การอ่าน Text file และ CSV และการ Data Binding(C#)
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 02
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 อัตราราคา คลิกที่นี่