SlideShare a Scribd company logo
1 of 18
Download to read offline
1
DATA CONTROL
GRIDVIEW
Điều khiển Gridiew cho phép trình bày dữ liệu theo dạng bảng dữ liệu.
Chọn GridView trong ngăn Data của cửa sổ ToolBox.
Có thể khai báo như sau: GridView gv1 = new GridView();
Và gắn lên webform : this.form1.Controls.Add(gv1);
Định dạng GridView: chọn mục Auto Format.. trong GridView Tasks
Sinh mã sau khi chọn:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
Có thể thay đổi màu nền (BackColor) cho các thẻ trên.
Thí dụ 1:
Chuyển dữ liệu vào GridView
Cách 1: Tạo điều khiển SqlDataSource, và đặt vào thuộc tính DataSource của GridView.
2
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString %>"
DeleteCommand="DELETE FROM [Categories] WHERE [CategoryID] = @CategoryID"
InsertCommand="INSERT INTO [Categories] ([CategoryName], [Description], [Picture])
VALUES (@CategoryName, @Description, @Picture)"
SelectCommand="SELECT * FROM [Categories]"
UpdateCommand="UPDATE [Categories] SET [CategoryName] = @CategoryName,
[Description] = @Description, [Picture] = @Picture WHERE [CategoryID] = @CategoryID">
<DeleteParameters>
<asp:Parameter Name="CategoryID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="CategoryName" Type="String" />
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="Picture" Type="Object" />
<asp:Parameter Name="CategoryID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="CategoryName" Type="String" />
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="Picture" Type="Object" />
</InsertParameters>
</asp:SqlDataSource>
Chuỗi ConnectionString lấy trong Web.config
<connectionStrings>
3
<add name="NORTHWNDConnectionString" connectionString="Data
Source=DELLP8700;Initial Catalog=NORTHWND;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Với khai báo thẻ:
ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString %>"
Khi gắn SqlDataSource vào GridView : DataSourceID="SqlDataSource1" , sẽ tạo tự động các
BoundControls (BoundField) trong thẻ <Columns>.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="CategoryID" DataSourceID="SqlDataSource1"
ForeColor="#333333" GridLines="None">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID"
InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName"
SortExpression="CategoryName" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
</Columns>
4
Kết quả thực thi:
Cách 2: Viết lệnh khởi tạo các điều khiển.
using System.Web.Configuration; // khai báo sử dụng WebConfigurationManager
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView gv1 = new GridView();
this.form1.Controls.Add(gv1);
FillData(gv1);
}
}
void FillData(GridView gridView)
{
SqlDataSource sqlDataSource = new SqlDataSource();
sqlDataSource.ConnectionString =
WebConfigurationManager.
ConnectionStrings["NORTHWNDConnectionString"].ConnectionString;
sqlDataSource.SelectCommandType = SqlDataSourceCommandType.Text;
sqlDataSource.SelectCommand = "select * from Products";
gridView.DataSource = sqlDataSource;
gridView.DataBind();
}
Kết quả thực thi:
5
Thuộc tính GridView
Phân trang
- Chọn AllowPaging=True.
- Cấu hình phân trang, chọn nhóm PagerSettings
Thuộc tính Mode: có 4 loại
Nếu chọn Numeric, chọn PageButtonCount chỉ định một lần xuất hiện bao nhiêu trang trên phân
đoạn, và PageSize chỉ định số lượng mẫu tin trên trang.
Thí dụ với Mode=Numeric; PageButtonCount=5; PageSize=10;
6
AllowSorting=True : cho phép sắp xếp mẫu tin theo cột chỉ định trên trang.
Các tiêu đề cột sẽ có gạch chân (underline).
Các thuộc tính xuất hiện các nút : Edit Delete Select
7
Khi thực hiện sẽ báo lỗi khi thiết kế điều khiển SqlDataSource nếu không có lựa chọn :
Nếu có lựa chọn sẽ xuất hiện:
8
Báo lỗi :
Trước khi sửa đổi: Click nút Edit  Update CanCel
Thay UnitPrice từ 99 thành 100
9
Các biến cố (events) quan trọng
PageIndexChanging - RowCancelingEdit
protected void CustomersGridView_PageIndexChanging(object sender,
GridViewPageEventArgs e)
{
// Cancel the paging operation if the user attempts to navigate
// to another page while the GridView control is in edit mode.
if (CustomersGridView.EditIndex != -1)
{
// Use the Cancel property to cancel the paging operation.
e.Cancel = true;
// Display an error message.
int newPageNumber = e.NewPageIndex + 1;
Message.Text = "Please update the record before moving to page " +
newPageNumber.ToString() + ".";
}
else
{
// Clear the error message.
Message.Text = "";
}
}
protected void CustomersGridView_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
// Clear the error message.
Message.Text = "";
}
10
RowEditing
protected void CustomersGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
// Get the country for the row being edited. For this example, the
// country is contained in the seventh column (index 6).
String country = CustomersGridView.Rows[e.NewEditIndex].Cells[5].Text;
// For this example, cancel the edit operation if the user attempts
// to edit the record of a customer from the Unites States.
if (country == "USA") { // Cancel the edit operation.
e.Cancel = true; Message.Text = "You cannot edit this record.";
}
else {
Message.Text = ""; }
}
Sorting - Sorted
11
protected void CustomersGridView_Sorting(object sender, GridViewSortEventArgs e)
{
// Cancel the sorting operation if the user attempts
// to sort by address.
if (e.SortExpression == "Address")
{
e.Cancel = true;
Message.Text = "You cannot sort by address.";
SortInformationLabel.Text = "";
}
else
{
Message.Text = "";
}
}
protected void CustomersGridView_Sorted(object sender, EventArgs e)
{
// Display the sort expression and sort direction.
SortInformationLabel.Text = "Sorting by " +
CustomersGridView.SortExpression.ToString() +
" in " + CustomersGridView.SortDirection.ToString() +
" order.";
}
RowDeleting
protected void CustomersGridView_RowDeleting(Object sender, GridViewDeleteEventArgs e)
{
// Cancel the delete operation if the user attempts to remove
// the last record from the GridView control.
if (CustomersGridView.Rows.Count <= 1)
{
e.Cancel = true;
Message.Text = "You must keep at least one record.";
}
Các dạng Fields trong thuộc tính Columns
12
Điều khiển BoundField
Trong trường hợp chỉ trình bày dữ liệu chọn lọc, sử dụng thuộc tính AutoGenerateColumn=false.
Ấn nút Add để thêm các BoundField, và đặt các giá trị thuộc tính của nó thích hợp với thuộc tính
tương ứng trong dữ liệu lấy từ SqlDataSource.
Điều khiển CheckBoxField
Dữ liệu có kiểu bit (true/false)
<asp:checkboxfield datafield="Nu"
headertext="Nu" SortExpression="Nu"/>
Điều khiển HyperLinkField
Khi có nhu cầu khai báo BoundColumn là liên kết.
<asp:gridview id="OrdersGridView" datasourceid="OrdersSqlDataSource"
autogeneratecolumns="False" runat="server">
<columns>
<asp:boundfield datafield="OrderID" headertext="Order ID"/>
<asp:hyperlinkfield datatextfield="ProductID" datanavigateurlfields="ProductID"
datanavigateurlformatstring="~/details.aspx?ProductID={0}"
headertext="ProductID" />
<asp:boundfield datafield="Quantity"
headertext="Quantity"/>
<asp:BoundField DataField="UnitPrice" DataFormatString="{0:c}"
HeaderText="Price" />
</columns>
</asp:gridview>
<asp:sqldatasource id="OrdersSqlDataSource"
selectcommand="SELECT [OrderID], [ProductID], [UnitPrice], [Quantity] FROM [Order
Details]"
connectionstring="<%$ ConnectionStrings:NORTHWNDConnectionString %>"
runat="server">
</asp:sqldatasource>
13
Điều khiển ButtonField
Cần chèn nút điều khiển vào GridView
Thí dụ:
<columns>
<asp:buttonfield buttontype="Button"
commandname="Select"
headertext="Select Customer"
text="Select"/>
<asp:boundfield datafield="CompanyName"
headertext="Company Name"/>
<asp:boundfield datafield="ContactName"
headertext="Contact Name"/>
</columns>
Xử lý sự kiện RowCommand xảy ra khi có một sự kiện nào đó trên webform.
onrowcommand="CustomersGridView_RowCommand"
protected void CustomersGridView_RowCommand(Object sender,
GridViewCommandEventArgs e)
{
// If multiple ButtonField column fields are used, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Select")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
14
int index = Convert.ToInt32(e.CommandArgument);
// Get the last name of the selected author from the appropriate
// cell in the GridView control.
GridViewRow selectedRow = CustomersGridView.Rows[index];
TableCell contactName = selectedRow.Cells[1];
string contact = contactName.Text;
// Display the selected author.
Message.Text = "You selected " + contact + ".";
}
}
CommandField
<asp:CommandField ShowSelectButton="True" ShowDeleteButton="True"
ShowEditButton="True" />
Nội dung SqlDataSource
<asp:sqldatasource id="CustomersSqlDataSource"
selectcommand="SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle]
FROM [Customers]"
connectionstring="<%$ ConnectionStrings:NORTHWNDConnectionString %>"
runat="server"
DeleteCommand="DELETE FROM [Customers] WHERE [CustomerID] = @CustomerID"
InsertCommand="INSERT INTO [Customers] ([CustomerID], [CompanyName],
[ContactName], [ContactTitle]) VALUES (@CustomerID, @CompanyName, @ContactName,
@ContactTitle)"
UpdateCommand="UPDATE [Customers] SET [CompanyName] = @CompanyName,
[ContactName] = @ContactName, [ContactTitle] = @ContactTitle WHERE [CustomerID] =
@CustomerID">
<DeleteParameters>
<asp:Parameter Name="CustomerID" Type="String" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="CompanyName" Type="String" />
<asp:Parameter Name="ContactName" Type="String" />
<asp:Parameter Name="ContactTitle" Type="String" />
<asp:Parameter Name="CustomerID" Type="String" />
15
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="CustomerID" Type="String" />
<asp:Parameter Name="CompanyName" Type="String" />
<asp:Parameter Name="ContactName" Type="String" />
<asp:Parameter Name="ContactTitle" Type="String" />
</InsertParameters>
</asp:sqldatasource>
Xử lý nút ButtonField và CommandField
protected void CustomersGridView_RowCommand(Object sender,
GridViewCommandEventArgs e)
{
// If multiple ButtonField column fields are used, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Select2")
16
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Get the last name of the selected author from the appropriate
// cell in the GridView control.
GridViewRow selectedRow = CustomersGridView.Rows[index];
TableCell contactName = selectedRow.Cells[2];
string contact = contactName.Text;
// Display the selected author.
Message.Text = "You selected " + contact + ".";
}
else
if (e.CommandName == "Select")
{
// Display the selected author.
Message.Text = "You selected CommandField Select.";
}
}
Xử lý nút Insert
Edit Template của GridView cho giao diện Insert
17
Bên trong EmptyDataTemplate là một điều khiển DetailsView
Chọn các thuộc tính thích hợp trong DetailsView
<EmptyDataTemplate>
<asp:DetailsView ID="DetailsView1" runat="server" CellPadding="4"
DataKeyNames="CustomerID"
DataSourceID="CustomersSqlDataSource" ForeColor="#333333"
Height="50px" oniteminserted="DetailsView1_ItemInserted" Width="216px"
DefaultMode="Insert">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
18
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<Fields>
<asp:CommandField ShowInsertButton="True" />
</Fields>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:DetailsView>
</EmptyDataTemplate>

More Related Content

Similar to Grid view

7 databinding-120306231825-phpapp02(1)
7 databinding-120306231825-phpapp02(1)7 databinding-120306231825-phpapp02(1)
7 databinding-120306231825-phpapp02(1)TI Anh
 
Chuong 07_ gắng kết dữ liệu asp.net
Chuong 07_ gắng kết dữ liệu asp.netChuong 07_ gắng kết dữ liệu asp.net
Chuong 07_ gắng kết dữ liệu asp.netThuyNguyenThi25
 
7.databinding
7.databinding7.databinding
7.databindingDao Uit
 
Lớp kết nối csdl dùng jdbc trong java
Lớp kết nối csdl dùng jdbc trong javaLớp kết nối csdl dùng jdbc trong java
Lớp kết nối csdl dùng jdbc trong javaANHMATTROI
 
Bài 6: Điều khiển DetailsView, FormView, ListView, DataPager
Bài 6: Điều khiển DetailsView, FormView, ListView, DataPagerBài 6: Điều khiển DetailsView, FormView, ListView, DataPager
Bài 6: Điều khiển DetailsView, FormView, ListView, DataPagerMasterCode.vn
 
The Art of Readable Code - DongPV
The Art of Readable Code - DongPVThe Art of Readable Code - DongPV
The Art of Readable Code - DongPVĐông Đô
 
6.adapterset
6.adapterset6.adapterset
6.adaptersetDao Uit
 
Hdth09 ltudql02-linq-e3
Hdth09 ltudql02-linq-e3Hdth09 ltudql02-linq-e3
Hdth09 ltudql02-linq-e3Dũng Đinh
 
04 chuong4-capnhatdulieu-140404115156-phpapp02
04 chuong4-capnhatdulieu-140404115156-phpapp0204 chuong4-capnhatdulieu-140404115156-phpapp02
04 chuong4-capnhatdulieu-140404115156-phpapp02huynhtrong774129
 
04 chuong 4 - cap nhat du lieu
04   chuong 4 - cap nhat du lieu04   chuong 4 - cap nhat du lieu
04 chuong 4 - cap nhat du lieutruong le hung
 

Similar to Grid view (20)

7 databinding-120306231825-phpapp02(1)
7 databinding-120306231825-phpapp02(1)7 databinding-120306231825-phpapp02(1)
7 databinding-120306231825-phpapp02(1)
 
Chuong 07_ gắng kết dữ liệu asp.net
Chuong 07_ gắng kết dữ liệu asp.netChuong 07_ gắng kết dữ liệu asp.net
Chuong 07_ gắng kết dữ liệu asp.net
 
7.databinding
7.databinding7.databinding
7.databinding
 
Lớp kết nối csdl dùng jdbc trong java
Lớp kết nối csdl dùng jdbc trong javaLớp kết nối csdl dùng jdbc trong java
Lớp kết nối csdl dùng jdbc trong java
 
Giới thiệu Yii Framework 1
Giới thiệu Yii Framework 1Giới thiệu Yii Framework 1
Giới thiệu Yii Framework 1
 
Aspnet 3.5 _05
Aspnet 3.5 _05Aspnet 3.5 _05
Aspnet 3.5 _05
 
Bài 6: Điều khiển DetailsView, FormView, ListView, DataPager
Bài 6: Điều khiển DetailsView, FormView, ListView, DataPagerBài 6: Điều khiển DetailsView, FormView, ListView, DataPager
Bài 6: Điều khiển DetailsView, FormView, ListView, DataPager
 
Aspnet 3.5 _04
Aspnet 3.5 _04Aspnet 3.5 _04
Aspnet 3.5 _04
 
C5. Model, DataSharing.pdf
C5. Model, DataSharing.pdfC5. Model, DataSharing.pdf
C5. Model, DataSharing.pdf
 
The Art of Readable Code - DongPV
The Art of Readable Code - DongPVThe Art of Readable Code - DongPV
The Art of Readable Code - DongPV
 
Ch06
Ch06Ch06
Ch06
 
6.adapterset
6.adapterset6.adapterset
6.adapterset
 
Hdth09 ltudql02-linq-e3
Hdth09 ltudql02-linq-e3Hdth09 ltudql02-linq-e3
Hdth09 ltudql02-linq-e3
 
Ung dung web chuong 4
Ung dung web  chuong 4Ung dung web  chuong 4
Ung dung web chuong 4
 
Aspnet 3.5 _02
Aspnet 3.5 _02Aspnet 3.5 _02
Aspnet 3.5 _02
 
Lab04 mapview
Lab04 mapviewLab04 mapview
Lab04 mapview
 
04 chuong4-capnhatdulieu-140404115156-phpapp02
04 chuong4-capnhatdulieu-140404115156-phpapp0204 chuong4-capnhatdulieu-140404115156-phpapp02
04 chuong4-capnhatdulieu-140404115156-phpapp02
 
04 chuong 4 - cap nhat du lieu
04   chuong 4 - cap nhat du lieu04   chuong 4 - cap nhat du lieu
04 chuong 4 - cap nhat du lieu
 
Asp.net 3.5 _7
Asp.net 3.5 _7Asp.net 3.5 _7
Asp.net 3.5 _7
 
Cach su dung data reader
Cach su dung data readerCach su dung data reader
Cach su dung data reader
 

Grid view

  • 1. 1 DATA CONTROL GRIDVIEW Điều khiển Gridiew cho phép trình bày dữ liệu theo dạng bảng dữ liệu. Chọn GridView trong ngăn Data của cửa sổ ToolBox. Có thể khai báo như sau: GridView gv1 = new GridView(); Và gắn lên webform : this.form1.Controls.Add(gv1); Định dạng GridView: chọn mục Auto Format.. trong GridView Tasks Sinh mã sau khi chọn: <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"> <RowStyle BackColor="#EFF3FB" /> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <EditRowStyle BackColor="#2461BF" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView> Có thể thay đổi màu nền (BackColor) cho các thẻ trên. Thí dụ 1: Chuyển dữ liệu vào GridView Cách 1: Tạo điều khiển SqlDataSource, và đặt vào thuộc tính DataSource của GridView.
  • 2. 2 <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString %>" DeleteCommand="DELETE FROM [Categories] WHERE [CategoryID] = @CategoryID" InsertCommand="INSERT INTO [Categories] ([CategoryName], [Description], [Picture]) VALUES (@CategoryName, @Description, @Picture)" SelectCommand="SELECT * FROM [Categories]" UpdateCommand="UPDATE [Categories] SET [CategoryName] = @CategoryName, [Description] = @Description, [Picture] = @Picture WHERE [CategoryID] = @CategoryID"> <DeleteParameters> <asp:Parameter Name="CategoryID" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="CategoryName" Type="String" /> <asp:Parameter Name="Description" Type="String" /> <asp:Parameter Name="Picture" Type="Object" /> <asp:Parameter Name="CategoryID" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="CategoryName" Type="String" /> <asp:Parameter Name="Description" Type="String" /> <asp:Parameter Name="Picture" Type="Object" /> </InsertParameters> </asp:SqlDataSource> Chuỗi ConnectionString lấy trong Web.config <connectionStrings>
  • 3. 3 <add name="NORTHWNDConnectionString" connectionString="Data Source=DELLP8700;Initial Catalog=NORTHWND;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> Với khai báo thẻ: ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString %>" Khi gắn SqlDataSource vào GridView : DataSourceID="SqlDataSource1" , sẽ tạo tự động các BoundControls (BoundField) trong thẻ <Columns>. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="CategoryID" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None"> <RowStyle BackColor="#EFF3FB" /> <Columns> <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" /> <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" /> <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" /> </Columns>
  • 4. 4 Kết quả thực thi: Cách 2: Viết lệnh khởi tạo các điều khiển. using System.Web.Configuration; // khai báo sử dụng WebConfigurationManager protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GridView gv1 = new GridView(); this.form1.Controls.Add(gv1); FillData(gv1); } } void FillData(GridView gridView) { SqlDataSource sqlDataSource = new SqlDataSource(); sqlDataSource.ConnectionString = WebConfigurationManager. ConnectionStrings["NORTHWNDConnectionString"].ConnectionString; sqlDataSource.SelectCommandType = SqlDataSourceCommandType.Text; sqlDataSource.SelectCommand = "select * from Products"; gridView.DataSource = sqlDataSource; gridView.DataBind(); } Kết quả thực thi:
  • 5. 5 Thuộc tính GridView Phân trang - Chọn AllowPaging=True. - Cấu hình phân trang, chọn nhóm PagerSettings Thuộc tính Mode: có 4 loại Nếu chọn Numeric, chọn PageButtonCount chỉ định một lần xuất hiện bao nhiêu trang trên phân đoạn, và PageSize chỉ định số lượng mẫu tin trên trang. Thí dụ với Mode=Numeric; PageButtonCount=5; PageSize=10;
  • 6. 6 AllowSorting=True : cho phép sắp xếp mẫu tin theo cột chỉ định trên trang. Các tiêu đề cột sẽ có gạch chân (underline). Các thuộc tính xuất hiện các nút : Edit Delete Select
  • 7. 7 Khi thực hiện sẽ báo lỗi khi thiết kế điều khiển SqlDataSource nếu không có lựa chọn : Nếu có lựa chọn sẽ xuất hiện:
  • 8. 8 Báo lỗi : Trước khi sửa đổi: Click nút Edit  Update CanCel Thay UnitPrice từ 99 thành 100
  • 9. 9 Các biến cố (events) quan trọng PageIndexChanging - RowCancelingEdit protected void CustomersGridView_PageIndexChanging(object sender, GridViewPageEventArgs e) { // Cancel the paging operation if the user attempts to navigate // to another page while the GridView control is in edit mode. if (CustomersGridView.EditIndex != -1) { // Use the Cancel property to cancel the paging operation. e.Cancel = true; // Display an error message. int newPageNumber = e.NewPageIndex + 1; Message.Text = "Please update the record before moving to page " + newPageNumber.ToString() + "."; } else { // Clear the error message. Message.Text = ""; } } protected void CustomersGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { // Clear the error message. Message.Text = ""; }
  • 10. 10 RowEditing protected void CustomersGridView_RowEditing(object sender, GridViewEditEventArgs e) { // Get the country for the row being edited. For this example, the // country is contained in the seventh column (index 6). String country = CustomersGridView.Rows[e.NewEditIndex].Cells[5].Text; // For this example, cancel the edit operation if the user attempts // to edit the record of a customer from the Unites States. if (country == "USA") { // Cancel the edit operation. e.Cancel = true; Message.Text = "You cannot edit this record."; } else { Message.Text = ""; } } Sorting - Sorted
  • 11. 11 protected void CustomersGridView_Sorting(object sender, GridViewSortEventArgs e) { // Cancel the sorting operation if the user attempts // to sort by address. if (e.SortExpression == "Address") { e.Cancel = true; Message.Text = "You cannot sort by address."; SortInformationLabel.Text = ""; } else { Message.Text = ""; } } protected void CustomersGridView_Sorted(object sender, EventArgs e) { // Display the sort expression and sort direction. SortInformationLabel.Text = "Sorting by " + CustomersGridView.SortExpression.ToString() + " in " + CustomersGridView.SortDirection.ToString() + " order."; } RowDeleting protected void CustomersGridView_RowDeleting(Object sender, GridViewDeleteEventArgs e) { // Cancel the delete operation if the user attempts to remove // the last record from the GridView control. if (CustomersGridView.Rows.Count <= 1) { e.Cancel = true; Message.Text = "You must keep at least one record."; } Các dạng Fields trong thuộc tính Columns
  • 12. 12 Điều khiển BoundField Trong trường hợp chỉ trình bày dữ liệu chọn lọc, sử dụng thuộc tính AutoGenerateColumn=false. Ấn nút Add để thêm các BoundField, và đặt các giá trị thuộc tính của nó thích hợp với thuộc tính tương ứng trong dữ liệu lấy từ SqlDataSource. Điều khiển CheckBoxField Dữ liệu có kiểu bit (true/false) <asp:checkboxfield datafield="Nu" headertext="Nu" SortExpression="Nu"/> Điều khiển HyperLinkField Khi có nhu cầu khai báo BoundColumn là liên kết. <asp:gridview id="OrdersGridView" datasourceid="OrdersSqlDataSource" autogeneratecolumns="False" runat="server"> <columns> <asp:boundfield datafield="OrderID" headertext="Order ID"/> <asp:hyperlinkfield datatextfield="ProductID" datanavigateurlfields="ProductID" datanavigateurlformatstring="~/details.aspx?ProductID={0}" headertext="ProductID" /> <asp:boundfield datafield="Quantity" headertext="Quantity"/> <asp:BoundField DataField="UnitPrice" DataFormatString="{0:c}" HeaderText="Price" /> </columns> </asp:gridview> <asp:sqldatasource id="OrdersSqlDataSource" selectcommand="SELECT [OrderID], [ProductID], [UnitPrice], [Quantity] FROM [Order Details]" connectionstring="<%$ ConnectionStrings:NORTHWNDConnectionString %>" runat="server"> </asp:sqldatasource>
  • 13. 13 Điều khiển ButtonField Cần chèn nút điều khiển vào GridView Thí dụ: <columns> <asp:buttonfield buttontype="Button" commandname="Select" headertext="Select Customer" text="Select"/> <asp:boundfield datafield="CompanyName" headertext="Company Name"/> <asp:boundfield datafield="ContactName" headertext="Contact Name"/> </columns> Xử lý sự kiện RowCommand xảy ra khi có một sự kiện nào đó trên webform. onrowcommand="CustomersGridView_RowCommand" protected void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e) { // If multiple ButtonField column fields are used, use the // CommandName property to determine which button was clicked. if (e.CommandName == "Select") { // Convert the row index stored in the CommandArgument // property to an Integer.
  • 14. 14 int index = Convert.ToInt32(e.CommandArgument); // Get the last name of the selected author from the appropriate // cell in the GridView control. GridViewRow selectedRow = CustomersGridView.Rows[index]; TableCell contactName = selectedRow.Cells[1]; string contact = contactName.Text; // Display the selected author. Message.Text = "You selected " + contact + "."; } } CommandField <asp:CommandField ShowSelectButton="True" ShowDeleteButton="True" ShowEditButton="True" /> Nội dung SqlDataSource <asp:sqldatasource id="CustomersSqlDataSource" selectcommand="SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle] FROM [Customers]" connectionstring="<%$ ConnectionStrings:NORTHWNDConnectionString %>" runat="server" DeleteCommand="DELETE FROM [Customers] WHERE [CustomerID] = @CustomerID" InsertCommand="INSERT INTO [Customers] ([CustomerID], [CompanyName], [ContactName], [ContactTitle]) VALUES (@CustomerID, @CompanyName, @ContactName, @ContactTitle)" UpdateCommand="UPDATE [Customers] SET [CompanyName] = @CompanyName, [ContactName] = @ContactName, [ContactTitle] = @ContactTitle WHERE [CustomerID] = @CustomerID"> <DeleteParameters> <asp:Parameter Name="CustomerID" Type="String" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="CompanyName" Type="String" /> <asp:Parameter Name="ContactName" Type="String" /> <asp:Parameter Name="ContactTitle" Type="String" /> <asp:Parameter Name="CustomerID" Type="String" />
  • 15. 15 </UpdateParameters> <InsertParameters> <asp:Parameter Name="CustomerID" Type="String" /> <asp:Parameter Name="CompanyName" Type="String" /> <asp:Parameter Name="ContactName" Type="String" /> <asp:Parameter Name="ContactTitle" Type="String" /> </InsertParameters> </asp:sqldatasource> Xử lý nút ButtonField và CommandField protected void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e) { // If multiple ButtonField column fields are used, use the // CommandName property to determine which button was clicked. if (e.CommandName == "Select2")
  • 16. 16 { // Convert the row index stored in the CommandArgument // property to an Integer. int index = Convert.ToInt32(e.CommandArgument); // Get the last name of the selected author from the appropriate // cell in the GridView control. GridViewRow selectedRow = CustomersGridView.Rows[index]; TableCell contactName = selectedRow.Cells[2]; string contact = contactName.Text; // Display the selected author. Message.Text = "You selected " + contact + "."; } else if (e.CommandName == "Select") { // Display the selected author. Message.Text = "You selected CommandField Select."; } } Xử lý nút Insert Edit Template của GridView cho giao diện Insert
  • 17. 17 Bên trong EmptyDataTemplate là một điều khiển DetailsView Chọn các thuộc tính thích hợp trong DetailsView <EmptyDataTemplate> <asp:DetailsView ID="DetailsView1" runat="server" CellPadding="4" DataKeyNames="CustomerID" DataSourceID="CustomersSqlDataSource" ForeColor="#333333" Height="50px" oniteminserted="DetailsView1_ItemInserted" Width="216px" DefaultMode="Insert"> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <CommandRowStyle BackColor="#E2DED6" Font-Bold="True" /> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> <FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
  • 18. 18 <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <Fields> <asp:CommandField ShowInsertButton="True" /> </Fields> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <EditRowStyle BackColor="#999999" /> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> </asp:DetailsView> </EmptyDataTemplate>