Ví dụ chương trình download tập tin bằng C#

Trong Topic này Tôi muốn hướng dẫn các bạn cách viết chương trình download tập tin từ internet

Ở đây Tôi tạo 3 Project (ứng với 3 kiểu viết, Tôi tạm gọi vậy)

Ta sẽ kết hợp Progressbar để hiển thị quá trình download tập tin:

A) Dùng Window Form

B) Dùng WPF

=========================================================

Nếu như không biết cách cập nhập progressbar thì chương trình của bạn có thể bị treo, nó sẽ không cho phép bạn tương tác tới các control khác cho tới khi download xong.

Chúng ta phải viết code để giải quyết vấn đề này. Tức là chương trình load thì cứ load, ta tương tác với các control khác thì cứ tương tác:

Tôi có giải thích trong coding nên trong topic Tôi không giải thích thêm nữa

A) Dùng Window Form:

Form 1: Dùng  component BackgroundWorker

Ta sẽ dùng component BackgroundWorker, trường hợp này hơi “lằng nhằng” chút xíu, nếu bạn cảm thấy “khó chịu” thì hãy qua Form2 để xem Tôi không sử dụng component BackgroundWorker.

Sau khi thiết kế xong giao diện như trên, bạn kéo thả component BackgroundWorker vào winform như hình bên dưới:

Cấu hình BackgroundWorker như trên, sau đó bạn mở qua tab Event của BackgroundWorker:

Để có được các sự kiện như trên thì bạn chỉ cần double click vào tên từng sự kiện là tự động nó phát sinh ra cho bạn.

Bây giờ bạn xem coding behind:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.IO;

using System.Net;

namespace ExampleBackgroundWorker

{

public partial class frmExample1 : Form

{

public frmExample1()

{

InitializeComponent();

}

private void btnTestDownload_Click(object sender, EventArgs e)

{

backgroundWorker1.RunWorkerAsync();

}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)

{

//Lấy đường dẫn muốn download

string sUrl =txtURL.Text.Trim();

//Đường dẫn lưu xuống ổ cứng

string sSave= txtSave.Text.Trim();

// Xác định dung lượng tập tin

Uri url = new Uri(sUrl);

System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

response.Close();

// Lấy dung lượng tập tin

Int64 iSize = response.ContentLength;

// Khởi tạo dung lượng download được từ URL

Int64 iRunningByteTotal = 0;

// Dùng Webclient để download

WebClient client = new WebClient();

// Mở URL để download

Stream streamRemote = client.OpenRead(new Uri(sUrl));

// Vừa đọc vừa lưu

Stream streamLocal = new FileStream(sSave, FileMode.Create, FileAccess.Write, FileShare.None);

// Tiến hành loop quá trình download, vừa load vừa lưu

int iByteSize = 0;

byte[] byteBuffer = new byte[iSize];

while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)

{

// Lưu byte xuống đường dẫn chỉ định

streamLocal.Write(byteBuffer, 0, iByteSize);

iRunningByteTotal += iByteSize;//cập nhập số byte đã load được

// Chuyển đổi ra tỉ lệ 100%

double dIndex = (double)(iRunningByteTotal);

double dTotal = (double)byteBuffer.Length;

double dProgressPercentage = (dIndex / dTotal);

int iProgressPercentage = (int)(dProgressPercentage * 100);

// Cập nhập progressbar

backgroundWorker1.ReportProgress(iProgressPercentage);

}

streamLocal.Close();

streamRemote.Close();

}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)

{

progressBar1.Value = e.ProgressPercentage;

lblPercentage.Text = e.ProgressPercentage + “%”;

}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

{

MessageBox.Show(“Đã download xong!”);

}

}

}

Form 2: Không dùng  component BackgroundWorker

Thiết kế giao diện tương tự như Form 1, nhưng không kéo thả component BackgroundWorker

Các bạn xem coding bên dưới:

using System;using

System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.IO;

using System.Net;

namespace ExampleBackgroundWorker

{

public partial class frmExample2 : Form

{

public frmExample2()

{

InitializeComponent();

}

private void btnDownload_Click(object sender, EventArgs e)

{

WebClient wc = new WebClient();

wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);

wc.DownloadFileAsync(new Uri(txtURL.Text.Trim()), txtSave.Text);

wc.DownloadFileCompleted+=new AsyncCompletedEventHandler(wc_DownloadFileCompleted);

}

public void wc_DownloadProgressChanged(Object sender, DownloadProgressChangedEventArgs e)

{

progressBar1.Value = e.ProgressPercentage;

lblPercentage.Text = e.ProgressPercentage + “%”;

}

public void wc_DownloadFileCompleted(Object sender, AsyncCompletedEventArgs e)

{

MessageBox.Show(“Download is completed”);

}

}

}

Trường hợp này có vẻ đơn giản hơn 1 xíu:

B) Dùng WPF:

Thiết kế giao diện tương tự, các bạn tùy thích thiết kế, nhưng nhớ đặt tên control cho đúng với tên mà trong code Tôi lấy ra sử dụng

Bạn xem code, Tôi vẫn sử dụng WebClient.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

using System.IO;

using System.Net;

namespace BackgroundWorker_WPF

{

/// <summary>

/// Interaction logic for MainWindow.xaml

/// </summary>

public partial class MainWindow : Window

{

public MainWindow()

{

InitializeComponent();

}

private void btnDownload_Click(object sender, RoutedEventArgs e)

{

WebClient wc = new WebClient();

wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);

wc.DownloadFileAsync(new Uri(txtURL.Text.Trim()), txtSave.Text);

wc.DownloadFileCompleted +=new System.ComponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted);

}

public void wc_DownloadProgressChanged(Object sender, DownloadProgressChangedEventArgs e)

{

progressBar1.Value = e.ProgressPercentage;

lblPercentage.Content = e.ProgressPercentage + “%”;

}

public void wc_DownloadFileCompleted(Object sender, System.ComponentModel.AsyncCompletedEventArgs e)

{

MessageBox.Show(“Download is completed”);

}

}

}

Link code đầy đủ:http://www.mediafire.com/?202z1o7v8r3badi

Chúc các bạn thành công.

Thông báo nộp bài tập trên Assembla

Thông báo dành cho các sinh viên lớp CDTH9ALT

Hiện này Thầy mới chỉ nhận được 5 bài tập nộp qua http://mediafire.com

Lý do: xem thông báo trước đây

Đã thông báo từ  lâu, sau ngày 10/04/2012 Thầy sẽ không nhận bài tập nữa

Thầy Thanh.

Cách sử dụng ListView Trong WPF

Topic này Tôi muốn hướng dẫn các bạn cách sử dụng ListView Trong WPF và cách Binding dữ liệu vào ListView

Vẫn sử dụng database mẫu là Petshop

http://www.mediafire.com/?19pyp63h5gzc49x, các bạn load về và Attach PetShop.mdf, chú ý là Tôi sử dụng SQL Server 2008

Trong phần này, các bạn sẽ tìm hiểu 6 cách thức sử dụng ListView trong WPF, lần lượt từ dễ tới khó.

Vì không có nhiều thời gian nên Tôi cũng không có giải thích chi tiết từng dòng lệnh như các Topic khác và lại nó cũng không khó khăn lắm, trong phần Binding dữ liệu lên ListView ( khi bấm vào nút lệnh  5, và 6 ) các bạn phải chú ý tên Cột trong bảng dữ liệu để đưa nó chính xác vào control lúc Binding. Nếu không hiểu phần nào thì các bạn Comment trực tiếp vào Topic này hoặc Email cho Tôi, Tôi sẽ trả lời trong thời gian sớm nhất có thể.

Đây là giao diện chính :

Tương ứng với từng nút lệnh là cách thức sử dụng ListView

Ở đây các bạn cũng sử dụng LINQ to SQL để sử dụng 2 bảng Product và Categories:

Còn đây là cấu trúc Tập tin và thư mục của Project:

Từ MainWindow.xaml, ta sẽ gọi các cửa sổ khác ứng với chức năng mà ta đã chọn

Các Bạn Bắt đầu đầu quan sát Tôi viết lệnh cho từng chức năng:

0) Cửa sổ MainWindow:

Phần XAML:

<Window x:Class=”ExampleListView.MainWindow”xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

Title=”Demo ListView” Height=”280″ Width=”356″>

<Window.Resources>

<LinearGradientBrush x:Key=”myButtonBrush”>

<GradientStop Color=”Lavender” Offset=”0.0″></GradientStop>

<GradientStop Color=”Pink” Offset=”0.5″></GradientStop>

<GradientStop Color=”LightGray” Offset=”1.0″></GradientStop>

</LinearGradientBrush>

</Window.Resources>

<GroupBox Header=”Ví dụ về ListView” BorderThickness=”4″ BorderBrush=”Red”>

<UniformGrid Rows=”2″ Columns=”3″ Height=”200″ Width=”297″>

<Button Content=”Simple” Background=”{DynamicResource ResourceKey=myButtonBrush}” Name=”btnSimple” Click=”btnSimple_Click”></Button>

<Button  Background=”{DynamicResource ResourceKey=myButtonBrush}” Name=”btnAddAndRemoveItem” Click=”btnAddAndRemoveItem_Click”>

<TextBlock>Add and<LineBreak/> Remove Item</TextBlock>

</Button>

<Button Content=”With Image”  Background=”{DynamicResource ResourceKey=myButtonBrush}” Name=”btnWithImage” Click=”btnWithImage_Click”></Button>

<Button  Background=”{DynamicResource ResourceKey=myButtonBrush}” Name=”btnWithImageAndCheckbox” Click=”btnWithImageAndCheckbox_Click”>

<TextBlock>Image and <LineBreak/>Checkbox</TextBlock>

</Button>

<Button  Background=”{DynamicResource ResourceKey=myButtonBrush}” Name=”btnWithGridView” Click=”btnWithGridView_Click”>

<TextBlock>With GridView<LineBreak/> Binding Coding</TextBlock>

</Button>

<Button  Background=”{DynamicResource ResourceKey=myButtonBrush}” Name=”btnWithGridViewAndCombobox” Click=”btnWithGridViewAndCombobox_Click”>

<TextBlock>With GridView<LineBreak/> Binding XAML</TextBlock>

</Button>

</UniformGrid>

</GroupBox>

</Window>

Phần Code behind:

using System;using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

namespace ExampleListView

{

/// <summary>

/// Interaction logic for MainWindow.xaml

/// </summary>

public partial class MainWindow : Window

{

public MainWindow()

{

InitializeComponent();

}

private void btnSimple_Click(object sender, RoutedEventArgs e)

{

ListViewSimple mylist = new ListViewSimple();

mylist.Show();

}

private void btnAddAndRemoveItem_Click(object sender, RoutedEventArgs e)

{

ListViewSimpleWithAddandRemoveItem mylist = new ListViewSimpleWithAddandRemoveItem();

mylist.Show();

}

private void btnWithImage_Click(object sender, RoutedEventArgs e)

{

ListViewWithImage mylist = new ListViewWithImage();

mylist.Show();

}

private void btnWithImageAndCheckbox_Click(object sender, RoutedEventArgs e)

{

ListViewWithImageAndCheckbox mylist = new ListViewWithImageAndCheckbox();

mylist.Show();

}

private void btnWithGridView_Click(object sender, RoutedEventArgs e)

{

ListViewWithGridView mylist = new ListViewWithGridView();

mylist.Show();

}

private void btnWithGridViewAndCombobox_Click(object sender, RoutedEventArgs e)

{

ListViewWithGridViewAndCombobox mylist = new ListViewWithGridViewAndCombobox();

mylist.Show();

}

}

}

1) Cửa sổ ListViewSimple:

Phần XAML:

<Window x:Class=”ExampleListView.ListViewSimple”xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

Title=”ListViewSimple” Height=”300″ Width=”300″ Loaded=”Window_Loaded”>

<Grid>

</Grid>

</Window>

Phần Code Behind:

using System;using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

namespace ExampleListView

{

/// <summary>

/// Interaction logic for ListViewSimple.xaml

/// </summary>

public partial class ListViewSimple : Window

{

public ListViewSimple()

{

InitializeComponent();

}

private void Window_Loaded(object sender, RoutedEventArgs e)

{

ListView lv = new ListView();

PetShopDataContext context = new PetShopDataContext();

var datas = from p in context.Products select p.Name;

lv.ItemsSource = datas;

this.Content = lv;

}

}

}

2) Cửa sổ ListViewSimpleWithAddandRemoveItem:

Phần XAML:

<Window x:Class=”ExampleListView.ListViewSimpleWithAddandRemoveItem”xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

Title=”ListViewSimpleWithAddandRemoveItem” Height=”381″ Width=”300″>

<StackPanel>

<StackPanel Orientation=”Vertical”>

<TextBox Width=”204″ Name=”txtName” Height=”21″ Background=”#FFDBA8A8″ AcceptsReturn=”True”></TextBox>

<Button Name=”btnAdd” Click=”btnAdd_Click” Height=”27″ Width=”73″>Thêm</Button>

<Button Name=”btnRemove” Click=”btnRemove_Click” Height=”32″ Width=”137″>Xóa Item Đang chọn</Button>

<Button Name=”btnRemoveAllSelected” Height=”33″ Width=”173″ Click=”btnRemoveAllSelected_Click”>Xóa Các Item Đang chọn</Button>

<Button Name=”btnRemoveAll” Height=”33″ Width=”209″ Click=”btnRemoveAll_Click”>Xóa hết luôn</Button>

</StackPanel>

<ScrollViewer Height=”200″ VerticalScrollBarVisibility=”Auto”>

<ListView Name=”lvProduct” SelectionMode=”Multiple”></ListView>

</ScrollViewer>

</StackPanel>

</Window>

Phần Code Behind:

using System;using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

namespace ExampleListView

{

/// <summary>

/// Interaction logic for ListViewSimpleWithAddandRemoveItem.xaml

/// </summary>

public partial class ListViewSimpleWithAddandRemoveItem : Window

{

public ListViewSimpleWithAddandRemoveItem()

{

InitializeComponent();

}

private void btnAdd_Click(object sender, RoutedEventArgs e)

{

lvProduct.Items.Add(txtName.Text);

txtName.Clear();

txtName.Focus();

}

private void btnRemove_Click(object sender, RoutedEventArgs e)

{

int nRemove=lvProduct.Items.IndexOf(lvProduct.SelectedItem);

lvProduct.Items.RemoveAt(nRemove);

//lvProduct.Items.Remove(lvProduct.SelectedItem);

}

private void btnRemoveAllSelected_Click(object sender, RoutedEventArgs e)

{

while (lvProduct.SelectedItems.Count > 0)

{

lvProduct.Items.Remove(lvProduct.SelectedItems[0]);

}

}

private void btnRemoveAll_Click(object sender, RoutedEventArgs e)

{

lvProduct.Items.Clear();

}

}

}

3) Cửa sổ ListViewWithImage:

Phần XAML:

<Window x:Class=”ExampleListView.ListViewWithImage”xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

Title=”ListViewWithImage” Height=”560″ Width=”456″>

<StackPanel>

<UniformGrid Rows=”2″ Columns=”2″>

<Label> Nhập Tên</Label>

<TextBox Name=”txtName”></TextBox>

<Label>Chọn hình ảnh</Label>

<StackPanel Orientation=”Horizontal”>

<TextBox Width=”150″ Height=”29″ Name=”txtPicture”></TextBox>

<Button Name=”btnPicture” Click=”btnPicture_Click”>Chọn hình</Button>

</StackPanel>

</UniformGrid>

<Button Name=”btnAdd” Height=”48″ Width=”225″ Click=”btnAdd_Click”> Thêm</Button>

<ScrollViewer VerticalScrollBarVisibility=”Auto” Height=”400″>

<ListView Name=”lvProduct”></ListView>

</ScrollViewer>

</StackPanel>

</Window>

Phần Code Behind:

using System;using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

namespace ExampleListView

{

/// <summary>

/// Interaction logic for ListViewWithImage.xaml

/// </summary>

public partial class ListViewWithImage : Window

{

public ListViewWithImage()

{

InitializeComponent();

}

private void btnPicture_Click(object sender, RoutedEventArgs e)

{

Microsoft.Win32.OpenFileDialog of = new Microsoft.Win32.OpenFileDialog();

of.Filter = “*.*|*.*”;

if (of.ShowDialog() == true)

{

txtPicture.Text = of.FileName;

}

}

private void btnAdd_Click(object sender, RoutedEventArgs e)

{

ListViewItem lvit = new ListViewItem();

lvit.Background = new SolidColorBrush(Colors.Wheat);

if(lvProduct.Items.Count%2==0)

lvit.Background = new SolidColorBrush(Colors.Lavender);

lvit.Foreground = new SolidColorBrush(Colors.Red);

lvit.FontFamily = new FontFamily(“Verdana”);

lvit.FontSize = 15;

StackPanel sp = new StackPanel();

sp.Orientation = Orientation.Horizontal;

Image img = new Image();

img.Source = new BitmapImage(new Uri(txtPicture.Text));

img.Height = 150;

img.Width = 150;

img.Stretch = Stretch.Fill;

TextBlock txt = new TextBlock();

txt.Text = txtName.Text;

sp.Children.Add(img);

sp.Children.Add(txt);

lvit.Content = sp;

lvProduct.Items.Add(lvit);

}

}

}

4) Cửa sổ ListViewWithImageAndCheckbox:

Phần XAML:

<Window x:Class=”ExampleListView.ListViewWithImageAndCheckbox”xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

Title=”ListViewWithImageAndCheckbox” Height=”601″ Width=”512″>

<StackPanel>

<UniformGrid Rows=”2″ Columns=”2″>

<Label>Nhập Tên</Label>

<TextBox Name=”txtName”></TextBox>

<Label>Chọn hình ảnh</Label>

<StackPanel Orientation=”Horizontal”>

<TextBox Width=”150″ Height=”29″ Name=”txtPicture”></TextBox>

<Button Name=”btnPicture” Click=”btnPicture_Click”>Chọn hình</Button>

</StackPanel>

</UniformGrid>

<Button Name=”btnAdd” Height=”48″ Width=”120″ Click=”btnAdd_Click”>Thêm</Button>

<Button Name=”btnShow” Height=”47″ Width=”147″ Click=”btnShow_Click”>Kiểm tra Item Checked</Button>

<ScrollViewer VerticalScrollBarVisibility=”Auto” Height=”400″>

<ListView Name=”lvProduct”></ListView>

</ScrollViewer>

</StackPanel>

</Window>

Phần Code Behind:

using System;using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

namespace ExampleListView

{

/// <summary>

/// Interaction logic for ListViewWithImageAndCheckbox.xaml

/// </summary>

public partial class ListViewWithImageAndCheckbox : Window

{

public ListViewWithImageAndCheckbox()

{

InitializeComponent();

}

private void btnPicture_Click(object sender, RoutedEventArgs e)

{

Microsoft.Win32.OpenFileDialog of = new Microsoft.Win32.OpenFileDialog();

of.Filter = “*.*|*.*”;

if (of.ShowDialog() == true)

{

txtPicture.Text = of.FileName;

}

}

private void btnAdd_Click(object sender, RoutedEventArgs e)

{

ListViewItem lvit = new ListViewItem();

lvit.Background = new SolidColorBrush(Colors.Wheat);

if (lvProduct.Items.Count % 2 == 0)

lvit.Background = new SolidColorBrush(Colors.Lavender);

lvit.Foreground = new SolidColorBrush(Colors.Red);

lvit.FontFamily = new FontFamily(“Verdana”);

lvit.FontSize = 15;

CheckBox chk = new CheckBox();

StackPanel sp = new StackPanel();

sp.Orientation = Orientation.Horizontal;

Image img = new Image();

img.Source = new BitmapImage(new Uri(txtPicture.Text));

img.Height = 50;

img.Width = 50;

img.Stretch = Stretch.Fill;

TextBlock txt = new TextBlock();

txt.Text = txtName.Text;

sp.Children.Add(img);

sp.Children.Add(txt);

chk.Content = sp;

lvit.Content = chk;

lvProduct.Items.Add(lvit);

}

private void btnShow_Click(object sender, RoutedEventArgs e)

{

foreach (ListViewItem item in lvProduct.Items)

{

CheckBox chk = (CheckBox)item.Content;

if (chk.IsChecked==true)

{

StackPanel st = (StackPanel)chk.Content;

TextBlock txt = (TextBlock)st.Children[1];

MessageBox.Show(txt.Text);

}

}

}

}

}

5) Cửa sổ ListViewWithGridView1:

Phần XAML:

<Window x:Class=”ExampleListView.ListViewWithGridView1″xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

Title=”ListViewWithGridView” Height=”287″ Width=”533″ Loaded=”Window_Loaded”>

<StackPanel>

<ScrollViewer VerticalScrollBarVisibility=”Auto” Height=”250″>

<ListView Height=”200″ HorizontalAlignment=”Left” Margin=”12,12,0,0″ Name=”listView1″ VerticalAlignment=”Top” Width=”486″>

<ListView.View>

<GridView>

<GridViewColumn Width=”140″ Header=”Mã danh mục”

DisplayMemberBinding=”{Binding CategoryId}”  />

<GridViewColumn Width=”140″ Header=”Tên Danh Mục”

DisplayMemberBinding=”{Binding Name}” />

<GridViewColumn Width=”140″ Header=”Mô tả”

DisplayMemberBinding=”{Binding Descn}” />

</GridView>

</ListView.View>

</ListView>

</ScrollViewer>

</StackPanel>

</Window>

Phần Code Behind:

using System;using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

namespace ExampleListView

{

/// <summary>

/// Interaction logic for ListViewWithGridView.xaml

/// </summary>

public partial class ListViewWithGridView1 : Window

{

public ListViewWithGridView()

{

InitializeComponent();

}

private void Window_Loaded(object sender, RoutedEventArgs e)

{

PetShopDataContext context = new PetShopDataContext();

listView1.ItemsSource = context.Categories;

}

}

}

6) Cửa sổ ListViewWithGridView2:

Phần XAML:

<Window x:Class=”ExampleListView.ListViewWithGridView2″xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

Title=”ListViewWithGridView2″ Height=”406″ Width=”532″

DataContext=”{Binding RelativeSource={RelativeSource Self}}” Loaded=”Window_Loaded”>

<StackPanel>

<ScrollViewer VerticalScrollBarVisibility=”Auto” Height=”250″>

<ListView Height=”200″ HorizontalAlignment=”Left” Margin=”12,12,0,0″ Name=”listView1″ VerticalAlignment=”Top” Width=”486″

ItemsSource=”{Binding CateCollection}”

>

<ListView.View>

<GridView>

<GridViewColumn Width=”140″ Header=”Mã danh mục”

DisplayMemberBinding=”{Binding CategoryId}”  />

<GridViewColumn Width=”140″ Header=”Tên Danh Mục”

DisplayMemberBinding=”{Binding Name}” />

<GridViewColumn Width=”140″ Header=”Mô tả”

DisplayMemberBinding=”{Binding Descn}” />

</GridView>

</ListView.View>

</ListView>

</ScrollViewer>

<StackPanel>

<UniformGrid Rows=”3″ Columns=”2″>

<Label>Mã danh mục</Label>

<TextBox Name=”txtId”></TextBox>

<Label>Tên danh mục</Label>

<TextBox Name=”txtName”></TextBox>

<Label>Mô Tả</Label>

<TextBox Name=”txtDes”></TextBox>

</UniformGrid>

<Button Name=”btnAdd” Height=”31″ Width=”175″ Click=”btnAdd_Click”>Thêm Danh mục</Button>

</StackPanel>

</StackPanel>

</Window>

Phần Code Behind:

using System;using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

using System.Collections.ObjectModel;

namespace ExampleListView

{

/// <summary>

/// Interaction logic for ListViewWithGridViewAndCombobox.xaml

/// </summary>

public partial class ListViewWithGridView2 : Window

{

public ListViewWithGridViewAndCombobox()

{

InitializeComponent();

}

ObservableCollection<Category> cateCollection =new ObservableCollection<Category>();

private void Window_Loaded(object sender, RoutedEventArgs e)

{

PetShopDataContext context = new PetShopDataContext();

foreach (Category c in context.Categories)

{

cateCollection.Add(c);

}

}

public ObservableCollection<Category> CateCollection

{

get { return cateCollection; }

}

private void btnAdd_Click(object sender, RoutedEventArgs e)

{

Category c = new Category();

c.CategoryId = txtId.Text;

c.Name = txtName.Text;

c.Descn = txtDes.Text;

cateCollection.Add(c);

}

}

}

Chúc các bạn thành công.

Source code mẫu đầy đủ: http://www.mediafire.com/?ab6aazuebsf2po2

Phần 1 – Kết nối các hệ cơ sở dữ liệu bằng Java

Yêu cầu: Các bạn phải rành về lập trình hướng đối tượng, tính kế thừa, tính đa hình thì mới hiểu được các phần hướng dẫn bên dưới. Tức là bạn phải khá về lập trình Java 1, nếu đọc mà vẫn không hiểu thì có thể email tới tranduythanh@hui.edu.vn Tôi sẽ giải thích những phần các bạn chưa hiểu.

———————————————————————————————————————

Phần 1: Kết nối Microsoft Access bằng Java

Phần 2: Kết nối Microsoft SQL Server 2008 bằng Java

Phần 3: Kết nối MySql bằng Java

———————————————————————————————————————

Topic này Tôi muốn hướng dẫn các bạn cách kết nối tới nhiều cơ sở dữ liệu khác nhau bằng ngôn ngữ lập trình Java

Các bạn sẽ được học đầy đủ trong môn Lập Trình Java 2.

Trong Topic này Tôi đặt ra một trường hợp là: Chúng ta có nhiều hệ cơ sở dữ liệu khác nhau ví dụ như Ms Access, SqlServer, MySQL… làm cách nào để viết các class Java thành các thư viện để kết nối tới các hệ cơ sở dữ liệu này?

Có rất nhiều mô hình, ở đây Tôi chỉ nhấn mạnh vào cách viết class để kết nối tới các CSDL mà thôi (không đề cập mô hình nào cả). Khi bạn rành rồi thì có thể sử dụng ORM hibernate để coding hoặc bất cứ loại nào. Nhưng trước tiên các bạn phải biết những kỹ thuật căn bản trước đã.

——————————————————————————————————————————————

Phần 1: Kết nối Microsoft Access bằng Java

Nếu bạn sử dụng MS Access 2003(đuôi là .mdb) thì không phải cài đặt thêm Driver

Còn nếu như bạn sử dụng MS Access 2007, 20120 (đuôi là .accdb)  thì các bạn cài đặt thêm:

2007 Office System Driver: Data Connectivity Components :

http://www.microsoft.com/download/en/details.aspx?id=23734

Những class nào bạn cần quan tâm trong phần 1 này:

Trong Connector bạn quan tâm tới classs CMsAccessConnector

Trong UI bạn quan tâm tới ConnectMsAccessUI

Tôi có chụp cấu trúc thư mục Project này như sau:

Mô hình class: Ở đây tôi tách làm 3 package để cho dễ quản lý.

– package Connector bao gồm các class kết nối và tương tác với các hệ cơ sở dữ liệu

– package Model dùng để mô hình hóa bảng dữ liệu thành các đối tượng.

– package UI cung cấp giao diện cho người sử dụng để tương tác với dữ liệu.

Mô hình của package Connector:

Mô hình của package Model:

Mô hình của package UI:

Cơ sở dữ liệu mẫu, ở đây Tôi làm 2 bảng lophoc và sinhvien ( các bạn chú ý là kiểu dữ liệu và kích thước là tương ứng cho cả 3 hệ cơ sở dữ liệu: Ms access, MySql và SqlServer…). Tôi muốn Demo sơ sơ chương trình quản lý sinh viên – lớp học.

Các bạn xem mô tả:

Trên đây là Tôi dùng Ms Access. Tương tự bạn làm cho Mysql, SqlServer. Có thể các bạn chưa thao tác với MySql bao giờ, Tôi sẽ hướng dẫn cách bạn download, cài đặt, cấu hình, sử dụng MySql Workbrench ở phần kế tiếp. Hiện tại bây giờ các bạn theo dõi Tôi hướng dẫn MS Access

Giao diện chính của chương trình như sau:

Tương ứng với mỗi nút lệnh “MS Access”, “SQL Server” , “My Sql” thì chương trình của chúng ta sẽ kết nối tới các hệ cơ sở dữ liệu đó.

Tôi sẽ giải thích chi tiết cách kết nối, cách tương tác với dữ liệu: Lấy dữ liệu, thêm, sửa, xóa, xử lý thống kê (in ấn dữ liệu)

Topic tương đối dài nên Tôi sẽ chia ra từng loại hệ cơ sở dữ liệu khác nhau. Chỉ cần các bạn cố gắng hiểu được cách tương tác tới 1 hệ cơ sở dữ liệu nào đó thì các hệ khác cũng tương tự, vấn đề chỉ nằm ở Logic lập trình của các bạn.

– Trong trường hợp kết nối tới MS Access, khi các bạn click chuột vào “Ms Access” thì sẽ có giao diện bên dưới:

Các bạn chú ý rằng. Giao diện trên được làm hết trong class AbstractConnectUI, Kể cả việc hiển thị dữ liệu.

Các bạn nhớ rằng. Vì chúng ta đang cố gắng tương tác với các hệ cơ sở dữ liệu khác nhau, tức là chỉ khác nhau ở nơi lưu trữ dữ liệu, còn giao diện và các nghiệp vụ thì hoàn toàn giống nhau.

Như vậy ứng với Ms Access thì trong ConnectMsAccessUI, bạn sẽ gọi các class Connector liên quan tới Ms Accesss.

hoặc là ứng với MySQL thì trong ConnectMySqlUI, bạn sẽ gọi các clsss Connector liên quan tới MySQL

Tức là chúng ta chỉ làm GIAO DIỆN 1 lần mà thôi, tùy vào việc sử dụng hệ cơ sở dữ liệu nào mà ta thay đổi hành vi khác nhau.

Các bạn phải rành về lập trình hướng đối tượng, tính kế thừa, tính đa hình thì việc tiếp thu sẽ nhanh chóng hơn.

Tôi đính kèm coding dưới này để các bạn tham khảo, Nếu như các bạn hiểu cách lấy dữ liệu từ Access rồi thì MySQl, SQL Server cũng sẽ tương tự. Topic này chỉ dừng lại ở việc truy suất dữ liệu. Trong ConnectMySqlUI, ConnectSqlServerUI Tôi cũng đã viết sẵn Code để truy vấn tới dữ liệu. Nếu bạn nào khá về Logic thì cố gắng đưa lên giao diện như trong Access, vài ngày nữa Tôi sẽ làm tiếp phần: Thêm, Sửa, Xóa, In ấn.

=================================================================

Package: tranduythanh.com.connector

=================================================================

class CConnector

package tranduythanh.com.connector;import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public abstract class CConnector

{

protected Connection m_Connection=null;

/**Hàm này dùng để kết nối tới các hệ sở dữ liệu

* Tùy vào từng Hệ CSDL chúng ta coding khác nhaucác lớp kế thừa từ

*/

public abstract Connection getConnect(String strServer,String strDatabase,String strUser,String strPwd);

/** Hàm này dùng để truy vấn dữ liệu,

* Connection con: đối tượng connnection

* String strSql: câu truy vấn

* Trả về ResultSet

*/

public ResultSet execQuery(Connection con,String strSql)

{

ResultSet rs=null;

try

{

Statement st=con.createStatement();

rs =st.executeQuery(strSql);

}

catch(SQLException ex)

{

ex.printStackTrace();

}

return rs;

}

/** Hàm này dùng để truy vấn dữ liệu,

* String strSql: câu truy vấn

* Trả về ResultSet

*/

public ResultSet execQuery(String strSql)

{

ResultSet rs=null;

try

{

Statement st=m_Connection.createStatement();

rs =st.executeQuery(strSql);

}

catch(SQLException ex)

{

ex.printStackTrace();

}

return rs;

}

/** Hàm này dùng cập nhật dữ liệu,

* Connection con: đối tượng connnection

* String strSql: câu truy vấn

* Nếu cập nhật thành công thì kết quả >0

*/

public int execNoneQuery(Connection con,String strSql)

{

int rec=0;

try

{

Statement st=con.createStatement();

rec=st.executeUpdate(strSql);

}

catch(SQLException ex)

{

ex.printStackTrace();

}

return rec;

}

/** Hàm này dùng cập nhật dữ liệu,

* String strSql: câu truy vấn

* Nếu cập nhật thành công thì kết quả >0

*/

public int execNoneQuery(String strSql)

{

int rec=0;

try

{

Statement st=m_Connection.createStatement();

rec=st.executeUpdate(strSql);

}

catch(SQLException ex)

{

ex.printStackTrace();

}

return rec;

}

/** Hàm này dùng đóng kết nối,

* Connection con: đối tượng connnection

*/

public void close(Connection con)

{

try

{

if(con!=null)

con.close();

}

catch(SQLException ex)

{

ex.printStackTrace();

}

}

/** Hàm này dùng đóng kết nối,

*/

public void close()

{

try

{

if(m_Connection!=null)

m_Connection.close();

}

catch(SQLException ex)

{

ex.printStackTrace();

}

}

}

class CMsAccessConnector

package tranduythanh.com.connector;import java.sql.Connection;

import java.sql.DriverManager;

public class CMsAccessConnector extends CConnector

{

/**

* Hàm dùng để kết nối tới MS Access

* strDatabase: tên CSDL

* Trả về Connection

**/

public Connection getConnect(String strServer,String strDatabase,String strUser,String strPwd)

{

try

{

String strConnect=”jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=”+strDatabase;

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

m_Connection= DriverManager.getConnection(strConnect);

}

catch(Exception e)

{

e.printStackTrace();

}

return m_Connection;

}

}

class CMySqlConnector

package tranduythanh.com.connector;import java.sql.Connection;import java.sql.SQLException;import java.util.Properties;

import com.mysql.jdbc.Driver;

public class CMySqlConnector  extends CConnector

{

/**

* Hàm dùng để kết nối tới MySQL

* strDatabase: tên CSDL

* Trả về Connection

**/

public Connection getConnect(String strServer,String strDatabase,String strUser,String strPwd)

{

String strConnect=”jdbc:mysql://”+strServer+”/”+strDatabase;

Properties pro=new Properties();

pro.put(“user”, strUser);

pro.put(“password”, strPwd);

try

{

com.mysql.jdbc.Driver driver=new Driver();

m_Connection=driver.connect(strConnect, pro);

}

catch(SQLException ex)

{

ex.printStackTrace();

}

return m_Connection;

}

}

class CSqlServerConnector

package tranduythanh.com.connector;import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

public class CSqlServerConnector extends CConnector

{

/**

* Hàm dùng để kết nối tới SQL Server

* strDatabase: tên CSDL

* Trả về Connection

**/

public Connection getConnect(String strServer,String strDatabase,String strUser,String strPwd)

{

try {

Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);

String connectionUrl = “jdbc:sqlserver://”+strServer+”;” +

“databaseName=”+strDatabase+”;user=”+strUser+”;password=”+strPwd+”;”;

System.out.println(“Successful”);

m_Connection= DriverManager.getConnection(connectionUrl);

System.out.println(“Successful”);

} catch (SQLException e) {

System.out.println(“SQL Exception: “+ e.toString());

} catch (ClassNotFoundException cE) {

System.out.println(“Class Not Found Exception: “+ cE.toString());

}

return m_Connection;

}

}

=================================================================

Package: tranduythanh.com.model

=================================================================

class Lophoc

package tranduythanh.com.model;import java.util.ArrayList;

public class Lophoc {

private String malop;

private String tenlop;

private int siso;

private ArrayList<Sinhvien> list=new ArrayList<Sinhvien>();

/**

* @return the list

*/

public ArrayList<Sinhvien> getList() {

return list;

}

public boolean addSinhvien(Sinhvien sv)

{

return list.add(sv);

}

public Sinhvien findSinhvienById(String masinhvien)

{

for(Sinhvien s: list)

{

if(s.getMasinhvien().equalsIgnoreCase(masinhvien))

return s;

}

return null;

}

public void removeSinhvien(String masinhvien)

{

Sinhvien sv=findSinhvienById(masinhvien);

list.remove(sv);

}

/**

* @param list the list to set

*/

public void setList(ArrayList<Sinhvien> list) {

this.list = list;

}

public Lophoc(String malop, String tenlop, int siso) {

super();

this.malop = malop;

this.tenlop = tenlop;

this.siso = siso;

}

public Lophoc() {

super();

}

/**

* @return the malop

*/

public String getMalop() {

return malop;

}

/**

* @param malop the malop to set

*/

public void setMalop(String malop) {

this.malop = malop;

}

/**

* @return the tenlop

*/

public String getTenlop() {

return tenlop;

}

/**

* @param tenlop the tenlop to set

*/

public void setTenlop(String tenlop) {

this.tenlop = tenlop;

}

/**

* @return the siso

*/

public int getSiso() {

return siso;

}

/**

* @param siso the siso to set

*/

public void setSiso(int siso) {

this.siso = siso;

}

@Override

public String toString() {

// TODO Auto-generated method stub

return this.tenlop +” (“+this.siso+”)”;

}

}

class Sinhvien

package tranduythanh.com.model;import java.sql.Date;

public class Sinhvien {

private String masinhvien;

private String malop;

private String hoten;

private Date namsinh;

private String diachi;

/**

* @return the masinhvien

*/

public String getMasinhvien() {

return masinhvien;

}

/**

* @param masinhvien the masinhvien to set

*/

public void setMasinhvien(String masinhvien) {

this.masinhvien = masinhvien;

}

/**

* @return the malop

*/

public String getMalop() {

return malop;

}

/**

* @param malop the malop to set

*/

public void setMalop(String malop) {

this.malop = malop;

}

/**

* @return the hoten

*/

public String getHoten() {

return hoten;

}

/**

* @param hoten the hoten to set

*/

public void setHoten(String hoten) {

this.hoten = hoten;

}

/**

* @return the namsinh

*/

public Date getNamsinh() {

return namsinh;

}

/**

* @param namsinh the namsinh to set

*/

public void setNamsinh(Date namsinh) {

this.namsinh = namsinh;

}

/**

* @return the diachi

*/

public String getDiachi() {

return diachi;

}

/**

* @param diachi the diachi to set

*/

public void setDiachi(String diachi) {

this.diachi = diachi;

}

public Sinhvien(String masinhvien, String malop, String hoten,

Date namsinh, String diachi) {

super();

this.masinhvien = masinhvien;

this.malop = malop;

this.hoten = hoten;

this.namsinh = namsinh;

this.diachi = diachi;

}

public Sinhvien() {

super();

}

public Sinhvien(String masinhvien, String hoten, Date namsinh, String diachi) {

super();

this.masinhvien = masinhvien;

this.hoten = hoten;

this.namsinh = namsinh;

this.diachi = diachi;

}

}

=================================================================

Package: tranduythanh.com.ui

=================================================================

class AbstractUI

package tranduythanh.com.ui;importjava.awt.Component;

import java.awt.Container;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

public abstract class AbstractUI extends JFrame {

private static final long serialVersionUID = 1L;

public AbstractUI(String title)

{

super(title);

}

public AbstractUI()

{

super(“Default …”);

}

public void doShow()

{

addControl();

addEventForAllControl();

doOwnerWindowFeature();

setVisible(true);

}

private void processJpanel(JPanel pn)

{

for(Component cp : pn.getComponents())

{

if(cp instanceof JButton)

{

((JButton) cp).addActionListener(new ProcessEvent());

}

else if(cp instanceof JPanel)

{

processJpanel((JPanel)cp);

}

}

}

public void addEventForAllControl()

{

Container con=getContentPane();

for(Component cp: con.getComponents())

{

if(cp instanceof JPanel)

{

processJpanel((JPanel)cp);

}

}

}

public abstract void addControl();

public abstract void doActionControl(Object o);

public abstract void doOwnerWindowFeature();

private class ProcessEvent implements ActionListener

{

@Override

public void actionPerformed(ActionEvent arg0) {

doActionControl(arg0.getSource());

}

}

}

class AbstractConnectUI

package tranduythanh.com.ui;importjava.awt.BorderLayout;

import java.awt.Color;

import java.awt.Container;

import java.awt.Dimension;

import java.awt.FlowLayout;

import java.awt.Font;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

import java.util.ArrayList;

import java.util.Vector;

import javax.swing.BorderFactory;

import javax.swing.BoxLayout;

import javax.swing.JButton;

import javax.swing.JComboBox;

import javax.swing.JLabel;

import javax.swing.JList;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JSplitPane;

import javax.swing.JTable;

import javax.swing.JTextArea;

import javax.swing.JTextField;

import javax.swing.border.TitledBorder;

import javax.swing.event.ListSelectionEvent;

import javax.swing.event.ListSelectionListener;

import javax.swing.table.DefaultTableModel;

import tranduythanh.com.connector.CConnector;

import tranduythanh.com.model.Lophoc;

import tranduythanh.com.model.Sinhvien;

public abstract class  AbstractConnectUI extends AbstractUI{

/**

*

*/

private static final long serialVersionUID = 1L;

protected static JList lstData;

protected JTable tblData;

protected DefaultTableModel dtmData;

protected JButton btnXoaLop,btnThemLop,btnSuaLop,btnThemSinhvien,btnLuuSinhvien,btnXoaSinhvien;

protected JTextField txtMasinhvien,txtTenSinhvien,txtNgaysinh,txtThangsinh,txtNamsinh;

protected JTextArea txtDiachi;

protected static JComboBox cboDanhsachlop;

protected static ArrayList<Lophoc> listLophoc;

protected static ArrayList<Sinhvien> listSinhvien;

protected static Lophoc lophocSelected;

protected static Sinhvien sinhvienSelected;

protected CConnector m_connector;

public AbstractConnectUI(String title)

{

super(title);

}

public AbstractConnectUI()

{

super(“Default …”);

}

@Override

public void addControl() {

// TODO Auto-generated method stub

JPanel pnBorder=new JPanel();

pnBorder.setLayout(new BorderLayout());

JPanel pnNorth=new JPanel();

JLabel lblTitle=new JLabel(“Quản lý Sinh Viên – Lớp Học”);

Font ftTitle=new Font(“arial”, Font.BOLD, 32);

lblTitle.setFont(ftTitle);

lblTitle.setForeground(Color.BLUE);

pnNorth.add(lblTitle);

pnBorder.add(pnNorth,BorderLayout.NORTH);

JPanel pnListLop=new JPanel();

JPanel pnListSinhvien=new JPanel();

JSplitPane slitPane=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, pnListLop, pnListSinhvien);

pnBorder.add(slitPane,BorderLayout.CENTER);

pnListLop.setLayout(new BorderLayout());

lstData=new JList();

TitledBorder cateborder=new TitledBorder(BorderFactory.createLineBorder(Color.RED), “Danh sách lớp học”);

pnListLop.setBorder(cateborder);

pnListLop.setPreferredSize(new Dimension(300, 0));

pnListLop.add(lstData,BorderLayout.CENTER);

JPanel pnListLopSouth=new JPanel();

btnThemLop =new JButton(“Thêm lớp”);

pnListLopSouth.add(btnThemLop);

btnSuaLop =new JButton(“Sửa lớp”);

pnListLopSouth.add(btnSuaLop);

btnXoaLop =new JButton(“Xóa lớp”);

pnListLopSouth.add(btnXoaLop);

pnListLop.add(pnListLopSouth,BorderLayout.SOUTH);

pnListSinhvien.setLayout(new BorderLayout());

JPanel pnSinhvienTitle=new JPanel();

JLabel lblSinhvienTitle=new JLabel(“Thông tin chi tiết”);

pnSinhvienTitle.add(lblSinhvienTitle);

pnListSinhvien.add(pnSinhvienTitle,BorderLayout.NORTH);

JPanel pnSinhvienTable=new JPanel();

pnSinhvienTable.setLayout(new BorderLayout());

pnListSinhvien.add(pnSinhvienTable,BorderLayout.CENTER);

dtmData =new DefaultTableModel();

dtmData.addColumn(“Mã Sinh Viên”);

dtmData.addColumn(“Tên Sinh Viên”);

dtmData.addColumn(“Ngày Sinh”);

dtmData.addColumn(“Lớp”);

dtmData.addColumn(“Địa chỉ”);

tblData=new JTable(dtmData);

JScrollPane sctblsinhvien=new JScrollPane(tblData);

pnSinhvienTable.add(sctblsinhvien,BorderLayout.CENTER);

JPanel pnSinhvienDetail=new JPanel();

pnListSinhvien.add(pnSinhvienDetail,BorderLayout.SOUTH);

pnSinhvienDetail.setLayout(new BoxLayout(pnSinhvienDetail, BoxLayout.Y_AXIS ));

JPanel pnLopList=new JPanel();

JLabel lblLopId=new JLabel(“Lớp học :”);

cboDanhsachlop=new JComboBox();

pnLopList.add(lblLopId);

pnLopList.add(cboDanhsachlop);

pnSinhvienDetail.add(pnLopList);

JPanel pnSinhvienId=new JPanel();

JLabel lblSinhvienId=new JLabel(“Mã sinh viên:”);

txtMasinhvien=new JTextField(20);

pnSinhvienId.add(lblSinhvienId);

pnSinhvienId.add(txtMasinhvien);

pnSinhvienDetail.add(pnSinhvienId);

JPanel pnSinhvienName=new JPanel();

JLabel lblSinhvienName=new JLabel(“Tên sinh viên:”);

txtTenSinhvien=new JTextField(20);

pnSinhvienName.add(lblSinhvienName);

pnSinhvienName.add(txtTenSinhvien);

pnSinhvienDetail.add(pnSinhvienName);

JPanel pnNgaysinh=new JPanel();

JLabel lblNgaysinh=new JLabel(“Ngày Sinh: “);

txtNgaysinh=new JTextField(3);

txtThangsinh=new JTextField(3);

txtNamsinh=new JTextField(4);

pnNgaysinh.add(lblNgaysinh);

JPanel pnNgaySinhChitiet=new JPanel();

pnNgaySinhChitiet.setLayout(new FlowLayout(FlowLayout.LEFT));

pnNgaySinhChitiet.add(txtNgaysinh);

pnNgaySinhChitiet.add(txtThangsinh);

pnNgaySinhChitiet.add(txtNamsinh);

JLabel lblNtnsFormat=new JLabel(“(dd-mm-yyyy)”);

lblNtnsFormat.setFont(new Font(“arial”,Font.ITALIC,10));

pnNgaySinhChitiet.add(lblNtnsFormat);

pnNgaysinh.add(pnNgaySinhChitiet);

pnSinhvienDetail.add(pnNgaysinh);

JPanel pnSinhvienDescription=new JPanel();

JLabel lblDescription=new JLabel(“Địa chỉ:”);

txtDiachi=new JTextArea(4, 20);

JScrollPane scare=new JScrollPane(txtDiachi);

pnSinhvienDescription.add(lblDescription);

pnSinhvienDescription.add(scare);

pnSinhvienDetail.add(pnSinhvienDescription);

JPanel pnButton=new JPanel();

btnThemSinhvien=new JButton(“Thêm SV”);

btnLuuSinhvien=new JButton(“Lưu SV”);

btnXoaSinhvien=new JButton(“Xóa SV”);

pnButton.add(btnThemSinhvien);

pnButton.add(btnLuuSinhvien);

pnButton.add(btnXoaSinhvien);

pnSinhvienDetail.add(pnButton);

cboDanhsachlop.setPreferredSize(txtMasinhvien.getPreferredSize());

lblLopId.setPreferredSize(lblSinhvienName.getPreferredSize());

lblDescription.setPreferredSize(lblSinhvienName.getPreferredSize());

lblNgaysinh.setPreferredSize(lblSinhvienName.getPreferredSize());

lblSinhvienId.setPreferredSize(lblSinhvienName.getPreferredSize());

Container con=getContentPane();

con.add(pnBorder);

lstData.addListSelectionListener(new ProcessEvent());

tblData.addMouseListener(new ProcessEvent());

}

@Override

public void doActionControl(Object o) {

// TODO Auto-generated method stub

if(o.equals(lstData))

{

showLopAndSinhvien();

}

else if(o.equals(tblData))

{

showChitietSinhvien();

}

}

private class ProcessEvent implements ListSelectionListener,MouseListener

{

@Override

public void valueChanged(ListSelectionEvent arg0) {

// TODO Auto-generated method stub

doActionControl(arg0.getSource());

}

@Override

public void mouseClicked(MouseEvent e) {

// TODO Auto-generated method stub

doActionControl(e.getSource());

}

@Override

public void mouseEntered(MouseEvent e) {

// TODO Auto-generated method stub

}

@Override

public void mouseExited(MouseEvent e) {

// TODO Auto-generated method stub

}

@Override

public void mousePressed(MouseEvent e) {

// TODO Auto-generated method stub

}

@Override

public void mouseReleased(MouseEvent e) {

// TODO Auto-generated method stub

}

}

@Override

public void doOwnerWindowFeature() {

// TODO Auto-generated method stub

setSize(800, 600);

setLocationRelativeTo(null);

setDefaultCloseOperation(DISPOSE_ON_CLOSE);

setResizable(false);

}

public abstract ArrayList<Lophoc> getListLop();

public abstract ArrayList<Sinhvien> getListSinhvienByIdLop(String malop);

public void showLopAndSinhvien()

{

Lophoc lh=(Lophoc ) lstData.getSelectedValue();

listSinhvien= getListSinhvienByIdLop(lh.getMalop());

lh.setList(listSinhvien);

lophocSelected=lh;

showListSinhvienIntoTable();

}

public void showListSinhvienIntoTable()

{

dtmData.setRowCount(0);

for(Sinhvien s: lophocSelected.getList())

{

Vector<String> vec=new Vector<String>();

vec.add(s.getMasinhvien());

vec.add(s.getHoten());

vec.add(s.getNamsinh().getDate()+”/”+(s.getNamsinh().getMonth()+1)+”/”+(s.getNamsinh().getYear()+1900));

vec.add(s.getMalop());

vec.add(s.getDiachi());

dtmData.addRow(vec);

}

}

public void showChitietSinhvien()

{

int row=tblData.getSelectedRow();

sinhvienSelected =listSinhvien.get(row);

txtMasinhvien.setText(sinhvienSelected.getMasinhvien());

txtTenSinhvien.setText(sinhvienSelected.getHoten());

txtDiachi.setText(sinhvienSelected.getDiachi());

txtNgaysinh.setText(sinhvienSelected.getNamsinh().getDate()+””);

txtThangsinh.setText((sinhvienSelected.getNamsinh().getMonth()+1)+””);

txtNamsinh.setText((sinhvienSelected.getNamsinh().getYear()+1900)+””);

cboDanhsachlop.setSelectedItem(lophocSelected);

}

public void updateLopList()

{

lstData.removeAll();

ArrayList<Lophoc> listlop=getListLop();

lstData.setListData(listlop.toArray());

lstData.updateUI();

cboDanhsachlop.removeAllItems();

for(Lophoc lh : listlop)

{

cboDanhsachlop.addItem(lh);

}

}

public void doComboboxSelected()

{

lophocSelected=(Lophoc) cboDanhsachlop.getSelectedItem();

}

}

class MainUI

package tranduythanh.com.ui;importjava.awt.BorderLayout;

import java.awt.Color;

import java.awt.Container;

import javax.swing.BorderFactory;

import javax.swing.BoxLayout;

import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.border.TitledBorder;

public class MainUI extends AbstractUI{

private static final long serialVersionUID = 1L;

JButton btnMsAcces,btnSqlServer,btnMysql,btnShutdown;

public MainUI(String title)

{

super(title);

}

public void addControl()

{

JPanel pnButton=new JPanel();

TitledBorder bor1=new TitledBorder(BorderFactory.createEtchedBorder(Color.RED, Color.BLUE), “Chọn loại kết nối”);

pnButton.setBorder(bor1);

JPanel pnAccess=new JPanel();

pnAccess.setLayout(new BoxLayout(pnAccess, BoxLayout.Y_AXIS));

ImageIcon icon=new ImageIcon(“images/ms-access.png”);

btnMsAcces=new JButton();

btnMsAcces.setIcon(icon);

pnAccess.add(btnMsAcces);

JLabel lblAccess=new JLabel(“Ms Access”);

pnAccess.add(lblAccess);

pnButton.add(pnAccess);

JPanel pnSqlServer=new JPanel();

pnSqlServer.setLayout(new BoxLayout(pnSqlServer, BoxLayout.Y_AXIS));

icon=new ImageIcon(“images/sqlserver.png”);

btnSqlServer=new JButton();

btnSqlServer.setIcon(icon);

pnSqlServer.add(btnSqlServer);

JLabel lblSqlServer=new JLabel(“Sql Server”);

pnSqlServer.add(lblSqlServer);

pnButton.add(pnSqlServer);

JPanel pnMysql=new JPanel();

pnMysql.setLayout(new BoxLayout(pnMysql, BoxLayout.Y_AXIS));

icon=new ImageIcon(“images/mysql.png”);

btnMysql=new JButton();

btnMysql.setIcon(icon);

pnMysql.add(btnMysql);

JLabel lblMysql=new JLabel(“My Sql”);

pnMysql.add(lblMysql);

pnButton.add(pnMysql);

Container con=getContentPane();

con.setLayout(new BorderLayout());

con.add(pnButton,BorderLayout.CENTER);

btnShutdown=new JButton();

icon=new ImageIcon(“images/shutdown.png”);

btnShutdown.setIcon(icon);

JPanel pnShutdown=new JPanel();

pnShutdown.setBackground(Color.PINK);

pnShutdown.add(btnShutdown);

TitledBorder bor2=new TitledBorder(BorderFactory.createEtchedBorder(Color.RED, Color.BLUE), “Thoát khỏi chương trình”);

bor2.setTitleColor(Color.BLUE);

bor2.setTitleJustification(TitledBorder.RIGHT);

pnShutdown.setBorder(bor2);

con.add(pnShutdown,BorderLayout.SOUTH);

btnMsAcces.setToolTipText(“Click vào đây để kết nối tới CSDL MS Access!”);

btnSqlServer.setToolTipText(“Click vào đây để kết nối tới CSDL SQL Server!”);

btnMysql.setToolTipText(“Click vào đây để kết nối tới CSDL My SQL!”);

btnShutdown.setToolTipText(“Click vào đây để thoát chương trình!”);

}

@Override

public void doActionControl(Object o) {

if(o.equals(btnMsAcces))

{

JOptionPane.showMessageDialog(null, “MS Access”);

ConnectMsAccessUI msAccessUI=new ConnectMsAccessUI(“MS Access Demo”);

msAccessUI.doShow();

}

else if(o.equals(btnMysql))

{

JOptionPane.showMessageDialog(null, “MySQL”);

ConnectMySqlUI mysqlUI=new ConnectMySqlUI(“MySQl Demo”);

mysqlUI.doShow();

}

else if(o.equals(btnSqlServer))

{

JOptionPane.showMessageDialog(null, “MS SqlServer”);

ConnectSqlServerUI ui=new ConnectSqlServerUI(“SQL server”);

ui.doShow();

}

else if(o.equals(btnShutdown))

{

int ret=JOptionPane.showConfirmDialog(this, “Muốnt thoát hả?”,”Thoát”,JOptionPane.YES_NO_OPTION);

if(ret==JOptionPane.YES_OPTION)

{

System.exit(0);

}

}

}

public static void main(String[] args) {

MainUI ui=new MainUI(“Demo Kết nối nhiều CSDL”);

ui.doShow();

}

@Override

public void doOwnerWindowFeature() {

// TODO Auto-generated method stub

setSize(400, 250);

setLocationRelativeTo(null);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setResizable(false);

}

}

class ConnectMsAccessUI

package tranduythanh.com.ui;importjava.sql.ResultSet;

import java.util.ArrayList;

import tranduythanh.com.connector.CMsAccessConnector;

import tranduythanh.com.model.Lophoc;

import tranduythanh.com.model.Sinhvien;

public class ConnectMsAccessUI extends AbstractConnectUI

{

/**

*

*/

private static final long serialVersionUID = 1L;

public ConnectMsAccessUI(String title)

{

super(title);

m_connector=new CMsAccessConnector();

}

@Override

public void addControl() {

// TODO Auto-generated method stub

super.addControl();

updateLopList();

}

@Override

public void doActionControl(Object o) {

// TODO Auto-generated method stub

super.doActionControl(o);

}

@Override

public void doOwnerWindowFeature() {

super.doOwnerWindowFeature();

}

@Override

public ArrayList<Lophoc> getListLop() {

// TODO Auto-generated method stub

ArrayList<Lophoc>listLop=new ArrayList<Lophoc>();

m_connector.getConnect(“”, “database\\quanlysinhvien.accdb”, “”, “”);

ResultSet rs= m_connector.execQuery(“select * from lophoc”);

try

{

while(rs.next())

{

Lophoc lh=new Lophoc(rs.getString(1), rs.getString(2), rs.getInt(3));

listLop.add(lh);

}

}

catch(Exception ex)

{

ex.printStackTrace();

}

return listLop;

}

@Override

public ArrayList<Sinhvien> getListSinhvienByIdLop(String malop) {

// TODO Auto-generated method stub

ArrayList<Sinhvien>listSv=new ArrayList<Sinhvien>();

m_connector.getConnect(“”, “database\\quanlysinhvien.accdb”, “”, “”);

ResultSet rs= m_connector.execQuery(“select * from sinhvien where malop='”+malop+”‘”);

try

{

while(rs.next())

{

Sinhvien sv=new Sinhvien(rs.getString(1), rs.getString(2), rs.getString(3), rs.getDate(4), rs.getString(5));

listSv.add(sv);

}

}

catch(Exception ex)

{

ex.printStackTrace();

}

return listSv;

}

}

class ConnectMySqlUI

package tranduythanh.com.ui;importjava.sql.ResultSet;

import java.util.ArrayList;

import tranduythanh.com.connector.CMySqlConnector;

import tranduythanh.com.model.Lophoc;

import tranduythanh.com.model.Sinhvien;

public class ConnectMySqlUI extends AbstractConnectUI{

private static final long serialVersionUID = 1L;

public ConnectMySqlUI(String title)

{

super(title);

CMySqlConnector con=new CMySqlConnector();

con.getConnect(“localhost”, “dbtest”, “root”, “hoilamgi”);

ResultSet rs= con.execQuery(“select * from tblemployee”);

try

{

while(rs.next())

{

System.out.println(rs.getInt(1) +” – “+rs.getString(2));

}

}

catch(Exception ex)

{

}

}

@Override

public void addControl() {

// TODO Auto-generated method stub

super.addControl();

}

@Override

public void doActionControl(Object o) {

// TODO Auto-generated method stub

}

@Override

public void doOwnerWindowFeature() {

// TODO Auto-generated method stub

super.doOwnerWindowFeature();

}

@Override

public ArrayList<Lophoc> getListLop() {

// TODO Auto-generated method stub

return null;

}

@Override

public ArrayList<Sinhvien> getListSinhvienByIdLop(String malop) {

// TODO Auto-generated method stub

return null;

}

}

class ConnectSqlServerUI

package tranduythanh.com.ui;importjava.sql.ResultSet;

importjava.util.ArrayList;

import tranduythanh.com.connector.CSqlServerConnector;

import tranduythanh.com.model.Lophoc;

import tranduythanh.com.model.Sinhvien;

public class ConnectSqlServerUI extends AbstractConnectUI{

/**

*

*/

private static final long serialVersionUID = 1L;

public ConnectSqlServerUI(String title)

{

CSqlServerConnector con=new CSqlServerConnector();

con.getConnect(“fithui”, “dbexample”, “sa”, “hoilamgi”);

ResultSet rs=con.execQuery(“select * from tblCustomer”);

try

{

while(rs.next())

{

System.out.println(rs.getString(2)+” – “+ rs.getString(4));

}

}

catch(Exception ex)

{

ex.printStackTrace();

}

}

@Override

public void addControl() {

// TODO Auto-generated method stub

super.addControl();

}

@Override

public void doActionControl(Object o) {

// TODO Auto-generated method stub

}

@Override

public void doOwnerWindowFeature() {

super.doOwnerWindowFeature();

}

@Override

public ArrayList<Lophoc> getListLop() {

// TODO Auto-generated method stub

return null;

}

@Override

public ArrayList<Sinhvien> getListSinhvienByIdLop(String malop) {

// TODO Auto-generated method stub

return null;

}

}

Các bạn ráng cài đặt để chạy được chương trình.

Chúc các bạn thành công.

Coding mẫu đầy đủ: http://www.mediafire.com/download.php?thpatqs1f0lpn2n (tham khảo chứ đừng copy paste code)

Link download thư viện kết nối tới MySQL: http://www.mediafire.com/?6cz23q7fmhmq1a1

Link download thư viện kết nối tới SQL Server: http://www.mediafire.com/?eiw554aacw2h4j9

Điểm bài tập môn F#

Thông báo dành cho lớp CDTH9ALT đang học môn Đồ Án Chuyên Nghành:

Thầy đã tổng hợp điểm bài tập F#

http://www.mediafire.com/?2zbr9x6xcxp5ho8

Một số em nợ học phí mà có nộp bài tập thì Thầy vẫn chấm bài, nhưng chú ý là các em vẫn không có điểm trong hệ thống EDU (tức là các em vẫn chưa học môn Đồ Án Chuyên Nghành)

Mọi khiếu nại về điểm môn F#, các em email tới tranduythanh@hui.edu.vn từ nay tới 11h trưa ngày 29/03/2012, sau thời gian này mọi khiếu nại sẽ không được giải quyết.

Chỉ những em nào đã nộp bài tập(nộp sớm) mới được khiếu nại.

Thầy Thanh.

Bảng điểm tổng kết thực hành Java 1

Thông báo dành cho lớp NCTH4B và NCTH4D.

(lớp CDTH12A Thầy Thắng sẽ tổng kết, các em liên hệ với thầy Thắng)

– Bảng điểm cuối cùng này cho biết những em nào được dự thi lý thuyết cuối kỳ.

– Thiếu bất cứ cột điểm nào hoặc chỉ cần 1 cột điểm <5 đều bị cấm thi lý thuyết cuối kỳ.

– Mọi khiếu nại về kết quả học tập, các em email tới tranduythanh@hui.edu.vn từ nay tới 11h trưa ngày 29/03/2012, sau thời gian này mọi khiếu nại về kết quả học tập đều không được giải quyết vì điểm đã nhập vào Hệ Thống EDU của nhà trường.

Link bảng tổng hợp điểm lớp NCTH4B:

http://www.mediafire.com/?m948buhxuybr83b(New)

Link bảng tổng hợp điểm lớp NCTH4D:

http://www.mediafire.com/?v30ep4o2p52uli2 (New)

Thầy Thanh.

Thông báo nghỉ học ngày 27/03/2012

Lớp CDTH9ALT nghỉ học môn Chuyên Đề Phát Triển Phần mềm vào tối thứ 3 ngày 27/03/2012

Lý do: nhà trường họp CBCNV

Tối thứ 5 đi học bình thường phòng A4.05

Lưu ý:

Tối thứ 3 học phòng X10.08

Tối thứ 5 học phòng A4.05

Nộp bài trên Assembla:

Hiện nay Assembla đã bị quá tải, Admin của Assembla đã “xử đẹp” tài nguyên mà Thầy đã tạo cho các em nộp bài( quá tải vì một số em đã upload dữ liệu không đúng yêu cầu lên Assembla, ví dụ như upload Office, WinXP…)

Vì vậy, mọi bài tập từ trước các em nén lại upload lên trang http://www.mediafire.com/ sau đó gửi link upload bài tập cho Thầy.

Chú ý: nhớ xóa toàn bộ .exe trước khi nén.

Ghi gửi email bài tập cho Thầy thì nhớ ghi rõ tên nhóm, thành viên trong nhóm để Thầy chấm bài.

Thầy Thanh.

Điểm thi lại cuối kỳ Java 1

Điểm thi lại Java 1 Lớp NCTH4B:

http://www.mediafire.com/?8uip06odgxli8ji

Điểm thi lại Java 1 Lớp NCTH4D:

http://www.mediafire.com/?hyy36zm4bx9nywu

Điểm thi lại Java 1 Lớp CDTH12A:

http://www.mediafire.com/?2nlq3xh96bl6byt

Chú ý:

Tất cả các sinh viên Nộp lab report Java 1 theo mẫu, hạn chót là 18h ngày 26/03/2012 (gia hạn). Sau hạn nộp bài này, mọi lý do về trễ hẹn đều không giải quyết. các sinh viên lưu ý.

Thông báo nộp Labreport đã đưa lên blog lâu rồi.

Làm Lab theo đúng những gì các em đã hiểu trong quá trình học tập, nếu mà LƯỜI BIẾNG cố tình sao chép lab của bạn thì điểm lab sẽ là 0 điểm cho những bài Lab giống nhau. Trong quá trình giảng dạy, Thầy đủ biết em nào hiểu bài tới đâu.

Thầy Thanh.

Điểm thi cuối kỳ Java 1 lớp NCTH4D

Điểm thi cuối kỳ Java 1- lớp NCTH4D:

http://www.mediafire.com/?ug4i7293rgeax25

Những em nào chưa vượt qua lần 1, sẽ thi lại vào sáng ngày mai 24/03/2012 tại phòng H9.3

Các sinh viên đã vượt qua cuối kỳ được nghỉ môn này(đã kết thúc môn, không phải đi học nữa)

Thầy Thanh.

Điểm thi cuối kỳ môn Java 1: CDTH12A và NCTH4B

Link xem điểm thi cuối kỳ môn Java 1

Lớp NCTH4B:

http://www.mediafire.com/?g2rsgmbjd5is4ix

Lớp CDTH12A:

http://www.mediafire.com/?ibcb4xwfdw39hb6

Tất cả những sinh viên có điểm <5 sẽ thi lại vào sáng Thứ 7 tuần này ngày 24/03/2012 tại phòng H9.3

Các sinh viên đã vượt qua cuối kỳ được nghỉ môn này(đã kết thúc môn, không phải đi học nữa)

Thầy Thanh.