using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Database : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strHTML = "";
strHTML+="<table border=\"0\" width=\"550\" cellspacing=\"1\" cellpadding=\"0\" bgcolor=\"#999966\" id=\"table2\">";
strHTML+=" <tr>";
strHTML += " <td bgcolor=\"#CC3300\" align=\"center\"><font color=\"#FFFFFF\">CustomerID</font></td>";
strHTML += " <td bgcolor=\"#CC3300\" align=\"center\"><font color=\"#FFFFFF\">CompanyName</font></td>";
strHTML += " <td bgcolor=\"#CC3300\" align=\"center\"><font color=\"#FFFFFF\">ContactName</font></td>";
strHTML += " <td bgcolor=\"#CC3300\" align=\"center\"><font color=\"#FFFFFF\">Country</font></td>";
strHTML+=" </tr>";
// Khai báo chuỗi kết nối
string connectString = @"Server =.\SQL2005;Initial Catalog=Northwind;User ID=sa;Password=******";
// Khai báo câu truy vấn
string sql = @"SELECT TOP 10 CustomerID, CompanyName, ContactName, Country FROM Customers ";
// Tạo một connection tới máy chủ
SqlConnection conn = new SqlConnection(connectString);
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
strHTML += " <tr>";
strHTML += " <td bgcolor=\"#FFFFFF\">" + reader[0]+ "</td>";
strHTML += " <td bgcolor=\"#FFFFFF\">" + reader[1] + "</td>";
strHTML += " <td bgcolor=\"#FFFFFF\">" + reader[2] + "</td>";
strHTML += " <td bgcolor=\"#FFFFFF\">" + reader[3] + "</td>";
strHTML += " </tr>";
}
reader.Close();//Đóng SqlDataReader
}
catch (SqlException ex)
{
Console.WriteLine("Error: " + ex);
}
finally
{
conn.Close();
}
strHTML += "</table>";
Literal1.Text = strHTML;
}
}
Kết quả thu được là các thông tin của trong câu lệnh<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataSetDemo.aspx.cs" Inherits="DataSetDemo" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>hmweb.com.vn</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC"
BorderStyle="None" BorderWidth="1px" CellPadding="3">
<RowStyle ForeColor="#000066" />
<FooterStyle BackColor="White" ForeColor="#000066" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>
Trong CodeFile (Code behind) bạn viết như sau:using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class DataSetDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtb = new DataTable();
dtb = DemoDataSet();
GridView1.DataSource = dtb;
GridView1.DataBind();
}
private DataTable DemoDataSet()
{
DataTable dtbTmp = new DataTable();
// Tạo connection string
string connString = @"Server =.\SQL2005;Initial Catalog=Northwind;User ID=sa;Password=******";
// Tạo SQL query
string sql = @"SELECT TOP 8 CustomerID, CompanyName, ContactName, Country FROM Customers ";
// Tạo connection
SqlConnection conn = new SqlConnection(connString);
try
{
// Mở kết nối
conn.Open();
// Tạo một Adapter
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
// Tạo DataSet
DataSet ds = new DataSet();
// Đổ dữ liệu DataSet
da.Fill(ds, "Customers");
// Tạo DataTable từ dataSet
dtbTmp = ds.Tables[0];
}
catch (Exception e)
{
// Bắt lỗi
Console.WriteLine(e.Message);
}
finally
{
// Đóng kết nối
conn.Close();
}
return dtbTmp;
}
}
Trong ví dụ trên mình dùng chỉ số index (ds.Tables[0]) để bạn hiểu rằng DataSet là một tập hợp nhiều DataTable. Khi bạn dùng da.Fill(ds, "Customers") Như vậy ngoài cách sử dụng index bạn cũng có thể sử dụng tên đã khai báo như sau: dtbTmp = ds.Tables["Customers"];private void DataSetInsertAndView()
{
// Tạo connection strin
string connString = @"Server =.\SQL2005;Initial Catalog=Northwind;User ID=sa;Password=******";
// Tạo SQL query
string ins = @"INSERT INTO employees (firstname, lastname, titleofcourtesy, city, country) VALUES
(@firstname, @lastname, @titleofcourtesy, @city, @country) ";
// Tạo connection
SqlConnection conn = new SqlConnection(connString);
try
{
// Tạo Adapter
SqlDataAdapter da = new SqlDataAdapter(qry, conn);
// Tạo và lấp đầy DataSet
DataSet ds = new DataSet();
da.Fill(ds, "employees");
// Lấy thông tin Table vào DataTable
DataTable dt = ds.Tables["employees"];
// Tạo thêm row mới
DataRow newRow = dt.NewRow();
newRow["firstname"] = "Bui";
newRow["lastname"] = "Hung";
newRow["titleofcourtesy"] = "AND";
newRow["city"] = "HaNoi";
newRow["country"] = "Viet Nam";
dt.Rows.Add(newRow);
// Hiển thị thông tin các rows trong DataSet sau khi thêm vào
foreach (DataRow row in dt.Rows)
{
Literal1.Text = row["firstname"].ToString().PadRight(15) + "|";
Literal1.Text += row["lastname"].ToString().PadLeft(15) + "|";
Literal1.Text += row["city"];
}
// Làm việc với Insert
SqlCommand cmd = new SqlCommand(ins, conn);
cmd.Parameters.Add("@firstname", SqlDbType.NVarChar, 10, "firstname");
cmd.Parameters.Add("@lastname", SqlDbType.NVarChar, 20, "lastname");
cmd.Parameters.Add("@titleofcourtesy", SqlDbType.NVarChar, 25, "titleofcourtesy");
cmd.Parameters.Add("@city", SqlDbType.NVarChar, 15, "city");
cmd.Parameters.Add("@country", SqlDbType.NVarChar, 15, "country");
// Tiến hành insert vào database Source
da.InsertCommand = cmd;
da.Update(ds, "employees");
}
catch (Exception e)
{
// Bắt lỗi
Console.WriteLine(e.Message);
}
finally
{
// Đóng kết nối
conn.Close();
}
}
Qua ví dụ trên bạn có thể nhận thấy DataSet khá linh hoạt, thông qua việc đổ dữ liệu từ dataSet đến các Tables, chúng ta có thể xem thông tin, chỉnh sửa thông tin và khi chỉnh sửa xong có thể update cho DataSource. Nếu các bạn nào tinh ý sẽ thấy quá trình trên thêm vào thực hiện quá dài cứ lập đi lặp lại việc cmd.Parameters.Add,để giải quyết vấn để này .NET cung cấp cho ta SqlCommandBuilder private void DataSetInsertAndView()
{
// Tạo connection string
string connString = @"Server =.\SQL2005;Initial Catalog=Northwind;User ID=sa;Password=******";
// Tạo SQL query
string ins = @"INSERT INTO employees (firstname, lastname, titleofcourtesy, city, country) VALUES
(@firstname, @lastname, @titleofcourtesy, @city, @country) ";
// Tạo connection
SqlConnection conn = new SqlConnection(connString);
try
{
// Tạo Adapter
SqlDataAdapter da = new SqlDataAdapter(qry, conn);
// Tạo commandbuider
SqlCommandBuilder cb = new SqlCommandBuilder(da);
// Tạo và lấp đầy DataSet
DataSet ds = new DataSet();
da.Fill(ds, "employees");
// Lấy thông tin Table vào DataTable
DataTable dt = ds.Tables["employees"];
// Tạo thêm row mới
DataRow newRow = dt.NewRow();
newRow["firstname"] = "Pi";
newRow["lastname"] = "Pi_Pi";
newRow["titleofcourtesy"] = "AND";
newRow["city"] = "UITS";
newRow["country"] = "Viet Nam";
dt.Rows.Add(newRow);
// Hiển thị thông tin các rows trong DataSet sau khi thêm vào
foreach (DataRow row in dt.Rows)
{
Literal1.Text = row["firstname"].ToString().PadRight(15) + "|";
Literal1.Text += row["lastname"].ToString().PadLeft(15) + "|";
Literal1.Text += row["city"];
}
//Nhờ sử dụng SqlCommandBuilder mà ta update rất nhanh
da.Update(ds, "employees");
}
catch (Exception e)
{
// Bắt lỗi
Console.WriteLine(e.Message);
}
finally
{
// Đóng kết nối
conn.Close();
}
}
// Trong hai ví dụ trên mình có tạo 1 <asp:Literal ID="Literal1" runat="server" /> để khi chạy sẽ hiển thị dữ liệu. Để chạy thử hàm trong ví dụ trên bạn chỉ cần đưa nó lên hàm Page_Load: DataSetInsertAndView();© Chia sẻ 2013 . Powered by Blogger . Blogger templates . New Blogger Templates