【发布时间】:2011-12-23 05:25:19
【问题描述】:
我加载一个 XML 文件,我将数据传输到数据集并使用 datagridview1 显示。
我有 3 个列:开始、结束和状态。
列开始的格式是日期时间,比如上午 8:00
列结束的格式也是日期时间,比如晚上 10:00
状态是两个值:ok 或 nok。
我需要将日期时间系统与开始列和结束列进行比较,如果日期系统在两个值之间,我会在行中显示 ok。我需要对每一行都这样做。好的,我需要将背景颜色更改为绿色,nok 将变为红色。 你可以帮帮我吗? .... 我在数据集和 datagridview 之间迷路了。 非常感谢
谢谢你们的帮助:我修改了一些代码,由你们提供:)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Globalization;
using System.Security.Permissions;
namespace tab
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataSet ds = new DataSet();
ds.ReadXml("C:\\Sites.xml");
int count = 0;
foreach (DataRow dr in ds.Tables[0].Rows)
{
string s1 = dr[0].ToString();
string s2 = dr[1].ToString();
string timeSys = DateTime.Now.ToString("hh:mm tt");
TimeSpan Start = DateTime.ParseExact(s1, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
TimeSpan End = DateTime.ParseExact(s2, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
TimeSpan Now = DateTime.ParseExact(timeSys, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
if (Start.Hours < Now.Hours && Now.Hours < End.Hours)
{
ds.Tables[0].Rows[count][2] = "OK";
}
else
{
ds.Tables[0].Rows[count][2] = "NOK";
}
count++;
}
dataGridView1.DataSource = ds.Tables[0];
for (int icount = 0; icount < dataGridView1.RowCount-1; icount++)
{
DataGridViewRow theRow = dataGridView1.Rows[icount];
if (theRow.Cells[2].Value.ToString() == "OK")
theRow.Cells[2].Style.BackColor = Color.Green;
else
theRow.Cells[2].Style.BackColor = Color.Red;
}
}
}
}
我还有一个问题,我没有看到 datagridview 中显示的颜色。
【问题讨论】:
-
这个问题需要一个有意义的标题,它不仅仅是标签的重复,但我对这个问题的理解还不够好,无法提供一个。有人吗?
-
如果颜色问题是唯一剩下的问题,请打开一个新问题。并查看 CellFormatting 事件。现在是定义单元格颜色的正确时机(例如,通过 e.CellStyle.BackColor)。
-
如果可行,请记住将其标记为答案(使用答案旁边的勾号)
标签: c# winforms datagridview