<%@ 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> 程序运行后结果如下: 而有的时候,我们可能要根据需要,对gridview中的数据进行特殊的显示,比如当某样商品库存为0时,要求gridview中以不同颜色进行显示,这时,可以按如下的方法进行: 首先,gridview提供了rowdatabound事件,该事件在gridview中每行被创建并且绑定到datasource控件后被触发,因此,我们可以利用该事件去检查库存是否为0,如果为0的话,将所在行的北京颜色设置为黄色,代码如下:
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; }} 首先,该事件首先检查,当前的行是否属于datarow类型的行,因为象gridview中的headerrow,footerrow等行,并不包含实际的数据,因此,我们不需要使用headerrow和footerrow,而为了取得库存unitesinstock的内容,通过使用databinder.eval的方法取出其内容,并转换为int类型,接着判断是否为0,如果为0的话,则设置其行的背景颜色为黄色。程序运行结果如下图所示:
Copyright @ 2007-2012 敏韬网(敏而好学,文韬武略--MinTao.Net)(学习笔记) Inc All Rights Reserved. 闵涛 E_mail:admin@mintao.net(欢迎提供学习资源)
鄂公网安备 42011102001154号
站长:MinTao ICP备案号:鄂ICP备11006601号-18