我有一个数据网格,其中包含时间值列,如0:15,0:30,0:45,1:00。
我想在row.Cells [2]的值时将背景颜色变为红色。字符串高于1:00所以它的3600.我想我需要将它转换为秒然后检查它是否比searchValue更高。我设法检查是否相等,但我不知道如何将其转换为秒,然后检查它是否更高。
SqlDataAdapter asdf;
DataTable ss;
asdf = new SqlDataAdapter("SELECT Firma, Czas, Opis,ID FROM Rok2016 WHERE Dzien=@DT AND Kto=@Kto", con);
asdf.SelectCommand.Parameters.AddWithValue("@DT", monthCalendar1.SelectionRange.Start.Date);
asdf.SelectCommand.Parameters.AddWithValue("@Kto", label3.Text);
ss = new DataTable();
asdf.Fill(ss);
dataGridView1.DataSource = ss;
String searchValue = "3600";
foreach (DataGridViewRow row in dataGridView1.Rows)
if (row.Cells[2].Value.ToString().Equals(searchValue))
{
row.DefaultCellStyle.BackColor = Color.Red;
}
答案 0 :(得分:0)
如果row.Cells[2].Value.ToString()
返回“00:15”或其他数字,如“01:14”或“15:53”,则可以将其分为小时和分钟值数组,将其解析为int (searchValueInSecondsString也是如此),将它转换为TimeSpan,得到所有的总秒数,最后你可以比较它,如下例所示:
String searchValueInSecondsString = "3600";
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var separateHourAndMinutes = row.Cells[2].Value.ToString().Split(':');
// safety first! ;)
if (separateHourAndMinutes.Length != 2)
{
Console.WriteLine("Wrong time value from grid!");
}
else
{
// safety second! ;)
if (int.TryParse(separateHourAndMinutes[0], out var hours) && int.TryParse(separateHourAndMinutes[1], out var minutes) && int.TryParse(searchValueInSecondsString, out var searchValue))
{
// if you want to make something red, if the search value and the time value are higher and equal, use >= instead of >
if (new TimeSpan(hours, minutes, 0).TotalSeconds > searchValue)
{
Console.WriteLine("I make it red!");
}
}
}
}
注意,我已将searchValue名称更改为searchValueInSecondsString,以了解搜索值需要的输入(秒和字符串)
P.S。:如果您想使用该代码轻松点击:https://dotnetfiddle.net/1OVfDy