How to overwrite a row in dataGridView if same DateTime is already in a row?

試著忘記壹切 提交于 2019-12-11 19:52:19

问题


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


回答1:


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.




回答2:


private void DataGridView_CellFormatting(object sender,
                System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
    // Check if this is in the column you want.
    if (dataGridView1.Columns[e.ColumnIndex].Name == "ColumnName")
    {
        // Check if the value is large enough to flag.
        if (Convert.ToInt32(e.Value).Tostring == "HIGH")
        {
            //Do what you want with the cell lets change color
            e.CellStyle.ForeColor = Color.Red;
            e.CellStyle.BackColor = Color.Yellow;
            e.CellStyle.Font =
            new Font(dataGridView1.DefaultCellStyle.Font, FontStyle.Bold);
        }
    }
}


来源:https://stackoverflow.com/questions/21818382/how-to-overwrite-a-row-in-datagridview-if-same-datetime-is-already-in-a-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!