如果相同的DateTime已经在一行,那么如何覆盖dataGridView中的一行? [英] How to overwrite a row in dataGridView if same DateTime is already in a row?
问题描述
这是迄今为止我的按钮上的代码:
DateTime thisDay = DateTime.Today;
dataGridView1.Rows.Add(thisDay.ToString(d));
我如何检查今天日期是否已写入行并覆盖当然这里不是很有意义,但是我会添加更多的单元格,在这种情况下也应该被覆盖),而不是用相同的日期创建一个新的行?
谢谢
您可以尝试这样:
string thisDay = DateTime.Today.ToString(d);
var duplicateRow =(from DataGridViewRow rowGridView1.Rows
where(string)row.Cells [columnName]。value == thisDay
select row).FirstOrDefault();
如果(duplicateRow!= null)
{
//发现重复行,更新它的列值
duplicateRow.Cells [columnName] Value = thisDay;
}
else
{
//重复行不存在,在此添加新行
}
使用linq选择具有特定列值等于当前日期的行。当没有行匹配条件时, .FirstOrDefault()
将返回 null
,否则它将返回第一个匹配的行。 / p>
This is the code on my button so far:
DateTime thisDay = DateTime.Today;
dataGridView1.Rows.Add(thisDay.ToString("d"));
How can I let it check if "todays" date is already written to a row and overwrite it (of course it doesnt make much sense here, but I will add more cells which also should be overwrite in that case) instead of making a new row with the same date?
Thanks
You can try this way :
string thisDay = DateTime.Today.ToString("d");
var duplicateRow = (from DataGridViewRow row in dataGridView1.Rows
where (string)row.Cells["columnName"].Value == thisDay
select row).FirstOrDefault();
if (duplicateRow != null)
{
//duplicate row found, update it's columns value
duplicateRow.Cells["columnName"].Value = thisDay;
}
else
{
//duplicate row doesn't exists, add new row here
}
That uses linq to select a row having particular column value equal current date. When no row match the criteria, .FirstOrDefault()
will return null
, else it will return first matched row.
这篇关于如果相同的DateTime已经在一行,那么如何覆盖dataGridView中的一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!