我有这样的 Gridview 和数据源:
<asp:SqlDataSource ID="SqlDataSource10" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT * FROM [data.csv]"></asp:SqlDataSource>
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px"
CellPadding="3" DataSourceID="SqlDataSource10" GridLines="Vertical"
Width="695px" Height="130px" onrowdatabound="GridView3_RowDataBound">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="H" HeaderText="H"
SortExpression="H" >
<HeaderStyle Width="115px" />
</asp:BoundField>
<asp:BoundField DataField="V" HeaderText="V"
SortExpression="V" >
<HeaderStyle Width="100px" />
</asp:BoundField>
<asp:BoundField DataField="F" HeaderText="F"
SortExpression="F" dataformatstring="{0:dd-MM-yyyy HH:mm}" >
<HeaderStyle Width="180px" />
</asp:BoundField>
<asp:BoundField DataField="V" HeaderText="V"
SortExpression="V" dataformatstring="{0:dd.MM.yyyy HH:mm}" >
<HeaderStyle Width="180px" />
</asp:BoundField>
我使用 csv 文件作为数据。如果日期值旧(2 小时),我必须更改背景色。
我可以对第一个日期列执行此操作,如下所示:
DateTime dt;
if (DateTime.TryParseExact(e.Row.Cells[1].Text, "dd.MM.YYYY HH:mm",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
if (dt <= DateTime.Now.AddHours(-2))
{
if (e.Row.Cells[0].Text.Contains("M"))
{
e.Row.Cells[1].BackColor = Color.LightCoral;
}
}
如果第一个日期列值早于 2 小时,则背景颜色发生变化。
我需要对 2. 日期列执行此操作。但与第一个日期值进行比较。如果根据第一个日期值第二个日期值早于 2 小时,则背景颜色更改:
我怎样才能做到这一点?
最佳答案
您可以使用 TimeSpan 类来计算迄今为止的差异。您可以执行此 OnRowDataBound 事件,请参见下文
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Checking the RowType of the Row
if (e.Row.RowType == DataControlRowType.DataRow)
{
DateTime firstDateValue = Convert.ToDateTime(e.Row.Cells[1].Text);
DateTime secondDateValue = Convert.ToDateTime(e.Row.Cells[2].Text);
TimeSpan timespan = secondDateValue - firstDateValue;
if (timespan.Hours > 2)
{
e.Row.BackColor = Color.Cyan;
}
}
}
关于c# - 如何比较两行的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29531632/