
ASP.NET 2.0中,新增加的gridview控件的确十分强大,弥补了在asp.net 1.1中,使用datagrid控件时的不足之处。因为在asp.net 1.1中,在使用datagrid时,很多情况下依然要编写大量的代码,十分不方便,而且有时需要很多技巧。而在asp.net 2.0中,很多情况下,使用gridview控件的话,甚至只需要拖拉控件,设置属性就可以了,不需要编写任何代码。在《使用ASP.NET 2.0中的GridView控件》和《ASP.NET2.0中用Gridview控件操作数据》中,已经对gridview控件做了一系列介绍,如果之前没有了解过gridview的读者,请先阅读这两篇文章。在本文中,将继续深入介绍gridview的一些使用技巧。
一 格式化gridview
和asp.net 1.1一样,gridview可以很方便地定制其样式,比如css,颜色等。要定制gridview的格式,十分简单,只需要鼠标右击gridview,在弹出的菜单中选择"AUTO FORMAT",则可以选择gridview的样式,内置了许多样式,如下图:
| <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server"> </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:SqlDataSource ID="productsDataSource" Runat="server" SelectCommand="SELECT [ProductID], [ProductName], [QuantityPerUnit], [UnitPrice], [UnitsInStock] FROM [Products]" ConnectionString="<%$ ConnectionStrings:NWConnectionString %>" DataSourceMode="DataReader"> </asp:SqlDataSource> <asp:GridView ID="productGridView" Runat="server" DataSourceID="productsDataSource" DataKeyNames="ProductID" AutoGenerateColumns="False" BorderWidth="1px" BackColor="#DEBA84" CellPadding="3" CellSpacing="2" BorderStyle="None" BorderColor="#DEBA84"> <FooterStyle ForeColor="#8C4510" BackColor="#F7DFB5"></FooterStyle> <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center"></PagerStyle> <HeaderStyle ForeColor="White" Font-Bold="True" BackColor="#A55129"></HeaderStyle> <Columns> <asp:BoundField ReadOnly="True" HeaderText="ID" InsertVisible="False" DataField="ProductID" SortExpression="ProductID"> <ItemStyle HorizontalAlign="Center"></ItemStyle> </asp:BoundField> <asp:BoundField HeaderText="Name" DataField="ProductName" SortExpression="ProductName"> </asp:BoundField> <asp:BoundField HeaderText="Qty/Unit" DataField="QuantityPerUnit" SortExpression="QuantityPerUnit"></asp:BoundField> <asp:BoundField HeaderText="Price/Unit" DataField="UnitPrice" SortExpression="UnitPrice" DataFormatString="{0:c}"> <ItemStyle HorizontalAlign="Right"></ItemStyle> </asp:BoundField> <asp:BoundField HeaderText="Units In Stock" DataField="UnitsInStock" SortExpression="UnitsInStock" DataFormatString="{0:d}"> <ItemStyle HorizontalAlign="Right"></ItemStyle> </asp:BoundField> </Columns> <SelectedRowStyle ForeColor="White" Font-Bold="True" BackColor="#738A9C"></SelectedRowStyle> <RowStyle ForeColor="#8C4510" BackColor="#FFF7E7"></RowStyle> </asp:GridView> </div> </form> </body> </html> |
| public void productsGridView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { int unitsInStock = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "UnitsInStock")); if (unitsInStock == 0) e.Row.BackColor = Color.Yellow; } } |