by
Neon Quach
29. July 2011 04:44
Gridview control là build in sẳn trong asp.net, nó cung cấp rất nhiều tiện ích tích hợp sẳn, cho nên đến nay vẫn có rất nhiều lập trình viên đã và đang sử dụng hằng ngày, khi format layout cho gridview chúng ta thường chọn Auto Format ở smart tag và thay đổi giao diện mà mình thích, điểm yếu của cách làm này là khi gridview render ra html code thường rất khó bảo trì và rất nặng để load.
Khắc phục vấn đề trên Khaled Atashbahar có 1 bài viết rất hay về cách định dạng cũng như trang trí lại cho gridview mà khắc phụ lại tình trạng bên trên sử dụng css. Chúng ta có thể download sample code tại đây.
Các thực hiện là thay đổi CSS CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt" như sau:
<div id="container">
<h1>ASP.NET GridView makeover using CSS</h1>
<asp:GridView ID="gvCustomres" runat="server" DataSourceID="customresDataSource" AutoGenerateColumns="False" GridLines="None" AllowPaging="true" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt">
<Columns>
<asp:BoundField DataField="CompanyName" HeaderText="Company Name" />
<asp:BoundField DataField="ContactName" HeaderText="Contact Name" />
<asp:BoundField DataField="ContactTitle" HeaderText="Contact Title" />
<asp:BoundField DataField="Address" HeaderText="Address" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
<asp:XmlDataSource ID="customresDataSource" runat="server" DataFile="~/App_Data/data.xml">
</asp:XmlDataSource>
</div>

CSS style sheet look like:
* {
padding: 0;
margin: 0;
}
body {
font: 11px Tahoma;
background-color: #F7F7E9;
}
h1 {
font: bold 32px Times;
color: #666;
text-align: center;
padding: 20px 0;
}
#container {
width: 700px;
margin: 10px auto;
}
.mGrid { width: 100%; background-color: #fff; margin: 5px 0 10px 0; border: solid 1px #525252; border-collapse:collapse; }
.mGrid td { padding: 2px; border: solid 1px #c1c1c1; color: #717171; }
.mGrid th { padding: 4px 2px; color: #fff; background: #424242 url(grd_head.png) repeat-x top; border-left: solid 1px #525252; font-size: 0.9em; }
.mGrid .alt { background: #fcfcfc url(grd_alt.png) repeat-x top; }
.mGrid .pgr {background: #424242 url(grd_pgr.png) repeat-x top; }
.mGrid .pgr table { margin: 5px 0; }
.mGrid .pgr td { border-width: 0; padding: 0 6px; border-left: solid 1px #666; font-weight: bold; color: #fff; line-height: 12px; }
.mGrid .pgr a { color: #666; text-decoration: none; }
.mGrid .pgr a:hover { color: #000; text-decoration: none; }

Ở đây css sử dụng 3 hình header, alternate và paper, bạn có thể thay đổi 3 files này theo cách bạn thích, nhưng với mình thì sử dụng 3 files này không có vấn đề gì.
http://code2code.googlecode.com/svn/trunk/GridViewMakeover
http://atashbahar.com/post/GridView-makeover-using-CSS.aspx