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.
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" />