2. Mục tiêu
Hiểu kết buộc dữ liệu
Repeater control
DataList control
Cập nhật dữ liệu qua form
Làm việc với dữ liệu XML
3. Data Binding (kết buộc dữ liệu)
Kết buộc dữ liệu là tiến trình liên kết dữ liệu lấy được vào
điều khiển để hiển thị
Dữ liệu có thể kết buộc đến tất cả các điều khiển dùng
biểu thức kết buộc dữ liệu được đặt giữa thể <%#......%>
Dữ liệu được kết buộc đến điều khiển bất cứ lúc nào
phương thức DataBind() được gọi
Kết buộc dữ liệu có thể thực hiện trên các kiểu dữ liệu
khác nhau như:
Các thuộc tính
Collections
Biểu thức
Kết quả của lời gọi hàm
4. Thuộc tính
ASP.NET cho phép các nhà phát triển kết buộc dữ liệu đến các biến public, thuộc
tính của trang hay thậm chí thuộc tính của các điều khiển khác
<html>
<title>DataBinding </title>
<script language="C#" runat="server">
void Page_Load(Object sender, EventArgs e)
{
Page.DataBind();
}
</script>
<form runat=server>
<center><b><u> DataBinding</center></b></u><br>
Enter a string and press tab
<br><br>
5. Thuộc tính
<asp:textbox id = "txtControl" AutoPostback="true" runat=
"server" /><br> <br>
<asp:label id = "lblControl" text = <
%#txtControl.Text%> runat = "server" /><br><br>
</form>
</html>
6. Biểu thức và phương thức
<%@ Import Namespace="System.Data" %>
<html>
<title>DataBinding Expressions</title>
<script language="C#" runat="server">
void Page_Load(Object Sender, EventArgs E)
{
Response.Write("<center><b><u>DataBinding
Expressions</center></b></u><br>");
if(!IsPostBack)
{
DataTable mydt = new DataTable();
DataRow mydr;
mydt.Columns.Add(new DataColumn ("Numbers",
typeof(Int32)));
7. Biểu thức và phương thức
for (int i=0;i<=5;i++)
{
mydr = mydt.NewRow();
mydr[0] = i;
mydt.Rows.Add(mydr);
}
dlMyList.DataSource = mydt;
dlMyList.DataBind();
}
}
int Square(int num)
{
int ans = num* num;
return ans;
}
8. Biểu thức và phương thức
int Cube(int num)
{
int ans = num*num*num;
return ans;
}
</script>
<form runat=server>
<asp:DataList id = "dlMyList" runat = "server">
<ItemTemplate>
Number : <%# ((DataRowView)Container.DataItem)
["Numbers"] %>
Square : <%# Square ((int) ((DataRowView)
Container.DataItem) ["Numbers"]) %>
Cube : <%# Cube ((int) ((DataRowView)
Container.DataItem) ["Numbers"]) %>
9. Biểu thức và phương thức
</ItemTemplate>
</asp:DataList>
</form>
</html>
10. Phương thức DataBinder.Eval()
Phương thức này dùng để đánh giá biểu thức kết buộc dữ liệu ở thời
gian thực thi và định dạng kết xuất được hiển thị trên trình duyệt.
A
r Tên chứa mục dữ liệu
g
u
m Tên trường
e
n
t Định dạng chuỗi
s
Example:
<%# DataBinder.Eval(Container.DataItem,"max_lvl","{0:c}") %>
11. Repeater
Là một container control, dùng để hiển thị danh sách các dữ liệu theo một mẫu
định dạng nào đó cho từng mục dữ liệu.
Mẫu định dạng (template) là một tập các phần tử HTML hay các điều khiển
dùng để định dạng hiển thị của điều khiển
T ItemTemplate
e
m AlternatingItemTemplate
p
l HeaderTemplate
a
t FooterTemplate
e
s SeparatorTemplate
18. DataList
Cho phép người dùng chỉ ra luồng dữ liệu
ItemTemplate
T AlternatingItemTemplate
e
m SelectedItemTemplate
p
EditItemTemplate
l
a HeaderTemplate
t
e FooterTemplate
s
SeparatorTemplate
22. DataList Kết xuất
</AlternatingItemTemplate>
</asp:DataList>
</form>
</body>
</html>
23. Quản lý dữ liệu trong
ASP.NET
Insert Update
DATA
Delete Select
24. Chèn dữ liệu
Đ ể chèn d ữ li ệ u 1.
: Nối kết CSDL
2. Tạo lệnh chèn trong CSDL
Thiết lập nối kết CSDL
mySqlCon = new SqlConnection ("server=SQLDB; uid= sa; pwd
=password; database=pubs");
Chèn dữ liệu qua đối tượng command
string myinsertCmd = "insert into publishers ( pub_id,
pub_name, city, state, country ) values (@pubid, @pubname,
@city, @state, @country)";
SqlCommand mySqlCom = new SqlCommand(myinsertCmd,
mySqlCon);
Tạo một tham số
SqlCom.Parameters.Add(new SqlParameter("@pubid",
SqlDbType.SmallInt, 2));
31. Cập nhật dữ liệu
Một cách để trình bày giao tiếp cho cập nhật dữ liệu là
cung cấp một tập dữ liệu đến người dùng và cho phép
người dùng chọn hàng để cập nhật
DataGrid có thể được dùng để hiển thị tất cả dữ liệu
cho người dùng, và người dùng chọn hàng để cập nhật
Người dùng có thể chọn hàng để cập nhật dùng
EditCommandColumn trong DataGrid
EditCommandColumn cung cấp liên kết cho 3 sự kiện:
Edit Command
Update Command
Cancel Command
32. Cập nhật dữ liệu
EditCommandColumn có thể thêm vào DataGrid
như sau:
<asp:datagrid id="dbgMyGrid" runat="server"
DataKeyField="pub_id"
OnUpdateCommand="dbgMyGrid_Update"
OnCancelCommand="dbgMyGrid_Cancel"
OnEditCommand="dbgMyGrid_Edit">
<Columns>
<asp:EditCommandColumn EditText="Edit"
CancelText="Cancel" UpdateText="Update" />
</Columns>
</asp:datagrid>
Sự kiện có thể được thực hiện khi người dùng chọn lệnh
trong EditCommandColumn
33. Cập nhật dữ liệu
EditItemIndex dùng để xác định vị trí của hàng
được cập nh
Sau khi giá trị hàng được gán cho EditItemIndex,
hàng có thể được biên tập
Ví dụ
public void dbgMyGrid_Edit(Object sender,
DataGridCommandEventArgs e)
{
dbgMyGrid.EditItemIndex = (int)e.Item.ItemIndex;
}
34. Cập nhật dữ liệu
Lấy khóa chính của hàng được chọn cập nhật
mySqlCmd.Parameters ["@pubid"].Value = dbgMyGrid.DataKeys
[(int)e.Item.ItemIndex];
Gán các giá trị thay đổi đến hàng qua các tham số
mySqlCmd.Parameters ["@pubname"].Value =
((TextBox)e.Item.Cells[2].Controls[0]).Text;
35. Cập nhật dữ liệu
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>
<HTML>
<title>Updating Data in a Database</title>
<script language="C#" runat="server">
SqlConnection mySqlCon;
protected void Page_Load(Object Src, EventArgs e)
{
Response.Write("<center><b><u>Updating
Data</center></b></u><br>");
mySqlCon = new SqlConnection ("server=SQLDB; uid=sa;
pwd=password;database=pubs");
if(!IsPostBack)
BindGrid();
}
36. Cập nhật dữ liệu
public void dbgMyGrid_Edit(Object sender,
DataGridCommandEventArgs e)
{
dbgMyGrid.Columns[0].HeaderText="Edit";
dbgMyGrid.EditItemIndex = (int)e.Item.ItemIndex;
BindGrid();
}
public void dbgMyGrid_Cancel(Object sender,
DataGridCommandEventArgs e)
{
dbgMyGrid.Columns[0].HeaderText="Cancel";
dbgMyGrid.EditItemIndex = -1;
BindGrid();
}
public void dbgMyGrid_Update(Object sender,
DataGridCommandEventArgs e
37. Cập nhật dữ liệu
{
dbgMyGrid.Columns[0].HeaderText="Update";
string strUpdate = "UPDATE Publishers SET pub_id = @pubid,
pub_name = @pubname, city = @city, state = @state, country =
@country WHERE pub_id = @pubid";
SqlCommand mySqlCmd = new SqlCommand(strUpdate,
mySqlCon);
mySqlCmd.Parameters.Add(new SqlParameter("@pubid",
SqlDbType.Char, 4));
mySqlCmd.Parameters.Add(new SqlParameter ("@pubname",
SqlDbType.VarChar, 40));
mySqlCmd.Parameters.Add(new SqlParameter ("@city",
SqlDbType.VarChar, 20));
mySqlCmd.Parameters.Add(new SqlParameter("@state",
SqlDbType.Char, 2));
mySqlCmd.Parameters.Add(new SqlParameter("@country",
SqlDbType.VarChar, 30));
39. Cập nhật dữ liệu
try
{
mySqlCmd.ExecuteNonQuery();
lblMessage.Text = "<b>Record Updated</b><br>" ;
dbgMyGrid.EditItemIndex = -1;
}
catch(SqlException exc)
{
if (exc.Number == 2627)
lblMessage.Text = "ERROR: A record already
exists with the same primary key";
else
lblMessage.Text = exc.ToString() + "ERROR:
Could not update record, please ensure the fields are
correctly filled out";
}
40. Cập nhật dữ liệu
mySqlCon.Close();
BindGrid();
}
public void BindGrid()
{
SqlDataAdapter mySqlda = new SqlDataAdapter ("select
* from publishers", mySqlCon);
DataSet myds = new DataSet();
mySqlda.Fill(myds, "publishers");
dbgMyGrid.DataSource = myds.Tables ["publishers"].
DefaultView;
dbgMyGrid.DataBind();
}
</script>
<body>
<form id="Form1" runat="server">
49. Quản lý dữ liệu XML
Schema <rootelement xmlns=” x-
schema:scheduledSchema.xsl”>
1 Mở tập tin
<rootelement xmlns = "x-schema:scheduledSchema.xsl">
FileStream myfs = new FileStream (Server.MapPath
("xmldatagrid.xml") ,FileMode.Open,FileAccess.Read);
2 Gán streamreader
StreamReader myreader = new StreamReader(myfs);
Đọc dữ liệu từ một streamreader
3
DataSet myds = new DataSet();
myds.ReadXml(myreader);
50. Quản lý dữ liệu XML
4 Kết buộc dự liệu
DataView mySource = new DataView(myds.Tables[0]);
DataGrid1.DataSource = mySource;
DataGrid1.DataBind();
Ví dụ:
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data" %>
<html>
<title>XML Data</title>
<script language="C#" runat="server">
void Page_Load(Object Src, EventArgs e)
{
DataSet myds = new DataSet();
51. XML Data in a DataGrid
FileStream myfs = new FileStream(Server.MapPath
("xmldatagrid.xml"),FileMode.Open, FileAccess.Read);
StreamReader myreader = new StreamReader(myfs);
myds.ReadXml(myreader);
myfs.Close();
DataView mySource = new DataView(myds.Tables[0]);
lblTableName.Text = mySource.Table.TableName;
dbgMyGrid.DataSource = mySource;
dbgMyGrid.DataBind();
}
</script>
<body>
<h3><font face="Arial">XML Data for Table:
<asp:label id="lblTableName" runat= "server"/></font>
</h3>
52. Hiển thị dữ liệu trong DataGrid
</h3>
<ASP:DataGrid id="dbgMyGrid" runat="server" />
</body>
</html>