Domanda

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

È stato utile?

Soluzione

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.

Altri suggerimenti

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);
        }
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top