如果相同的DateTime已经在一行,那么如何覆盖dataGridView中的一行? [英] How to overwrite a row in dataGridView if same DateTime is already in a row?

查看:165
本文介绍了如果相同的DateTime已经在一行,那么如何覆盖dataGridView中的一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是迄今为止我的按钮上的代码:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆