这篇文章便论述关于如何在GridView随某行某列值的改变时(这些值是空的或不是空的或是其它某些值等)其背景色及文本颜色也随之改变的问题 根据某列的值改变其样式最好的方法是在GridView的DataRowBound事件中想办法在GridView中的行绑定数据后将立即执行DataRowBound事件DataRowBound事件使用GridViewRowEventargs类作为事件变量通过事件变量你能够利用GridViewRowEventArgs属性操作已经绑定数据的行 protected void GridView_RowDataBound(object sender GridViewRowEventArgs e) { GridViewRow row = eRow; } Row将返回TableRow类中的一个GridViewRow对象 绑定的Row有几种不同的类型例如DataRow EmptyDataRow Footer Header Pager 和 Separator通过GridView的RowType属性可以得到当前行的行类型RowType是一组DataControlRow枚举 看下面的代码示例检测GridView列出的行是否为一个标准类型的行 protected void GridView_RowDataBound(object sender GridViewRowEventArgs e) { if (eRowRowType == DataControlRowTypeDataRow) { //Do something! } } 可以使用Row的Cells属性得到其Cells它将返回一个TableCellCollection对象然后通过TableCellCollection索引得到特定的CellsTableCellcollection索引将返回一个TabelCell对象对应于Row中的一个Cell protected void GridView_RowDataBound(object sender GridViewRowEventArgs e) { if (eRowRowType == DataControlRowTypeDataRow) { string value = eRowCells[]Text; } } 现在你已经明白了如何得到GridView中某行某列的值那么根据值的变化改变其样式就比较容易了以下示例使用 Northwind 数据库通过检测第四列(UnitPrice)的值是否大于将其颜色改变为红色 <%@ Page Language=C#%> <%@ Import Namespace=SystemDrawing %> <!DOCTYPE html PUBLIC //WC//DTD XHTML //EN http://wwwworg/TR/xhtml/DTD/xhtmldtd> <script runat=server> protected void GridView_RowDataBound(object sender GridViewRowEventArgs e) { if (eRowRowType == DataControlRowTypeDataRow) { if (DecimalParse(eRowCells[]Text) > ) eRowCells[]BackColor = ColorRed; } } </script> <html xmlns=http://wwwworg//xhtml > <head runat=server> <title>Untitled Page</title> </head> <body> <form id=form runat=server> <div> <asp:GridView ID=GridView runat=server DataSourceID=SqlDataSource AutoGenerateColumns=FalseDataKeyNames=ProductIDOnRowDataBound=GridView_RowDataBound> <Columns> <asp:BoundField ReadOnly=True HeaderText=ProductID InsertVisible=FalseDataField=ProductID SortExpression=ProductID /> <asp:BoundField HeaderText=ProductName DataField=ProductName SortExpression=ProductName /> <asp:BoundField HeaderText=QuantityPerUnit DataField=QuantityPerUnit SortExpression=QuantityPerUnit /> <asp:BoundField HeaderText=UnitPrice DataField=UnitPrice SortExpression=UnitPrice /> </Columns> </asp:GridView> <asp:SqlDataSource ID=SqlDataSource runat=server SelectCommand=SELECT [ProductID] [ProductName] [QuantityPerUnit] [UnitPrice] FROM [Alphabetical list of products] ConnectionString=<%$ ConnectionStrings:AppConnectionString %> /> </div> </form> </body> </html> |