有在论坛上看到一个问题,就是在Gridview控件中,需要对几个列的数值进行比较,原问题如下:
先在数据库中准备数据:
CREATE TABLE [dbo].[RecordTime] ( Id INT IDENTITY(1,1) PRIMARY KEY, Time1 DATETIME, Time2 DATETIME, Time3 DATETIME, Time4 DATETIME ) GO INSERT INTO [dbo].[RecordTime] VALUES ('2015-05-11 09:48','2015-05-20 10:08','2015-05-13 14:48','2015-05-19 08:48'), ('2015-05-10 14:48','2015-05-01 10:02','2015-05-20 12:48','2015-05-20 10:20'), ('2015-05-20 10:31','2015-05-03 10:40','2015-05-14 10:40','2015-05-25 09:48') GO CREATE PROCEDURE [dbo].[usp_RecordTime_GetAll] AS SELECT [Id],[Time1],[Time2],[Time3],[Time4] FROM [dbo].[RecordTime] GO
然后可以在.aspx.cs代码页中实现OnRowDataBound="GridView1_RowDataBound"事件:
.aspx.cs代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Insus.NET; using System.Data; using System.Drawing; public partial class _Default : System.Web.UI.Page { RecordTime rt = new RecordTime(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) Data_Binding(); } private void Data_Binding() { this.GridView1.DataSource = rt.GetRecordTime(); this.GridView1.DataBind(); } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType != DataControlRowType.DataRow) return; DataRowView drv = (DataRowView)e.Row.DataItem; List<DateTime> lDT = new List<DateTime>(); lDT.Add(Convert.ToDateTime(drv["Time1"])); lDT.Add(Convert.ToDateTime(drv["Time2"])); lDT.Add(Convert.ToDateTime(drv["Time3"])); lDT.Add(Convert.ToDateTime(drv["Time4"])); DateTime dt = lDT.Max<DateTime>(); int i = lDT.IndexOf(dt); int actualIdx = i + 1; e.Row.Cells[actualIdx].ForeColor = Color.FromName("red"); } }