【问题标题】:How to overwrite a row in dataGridView if same DateTime is already in a row?如果相同的 DateTime 已经在一行中,如何覆盖 dataGridView 中的一行?
【发布时间】:2014-03-16 02:49:16
【问题描述】:

到目前为止,这是我按钮上的代码:

DateTime thisDay = DateTime.Today;
dataGridView1.Rows.Add(thisDay.ToString("d"));

如何让它检查“今天”日期是否已经写入一行并覆盖它(当然在这里没有多大意义,但我会添加更多在这种情况下也应该覆盖的单元格)而不是在同一日期创建一个新行?

谢谢

【问题讨论】:

    标签: c# datetime datagridview row overwrite


    【解决方案1】:
    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);
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      你可以试试这个方法:

      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
      }
      

      使用 linq 选择特定列值等于当前日期的行。当没有符合条件的行时,.FirstOrDefault() 将返回null,否则将返回第一个匹配的行。

      【讨论】:

      • 我试图像这样插入另一列(在这种情况下我也想覆盖):if (duplicateRow != null) { //duplicate row found, update it's columns value duplicateRow.Cells["column1"].Value = thisDay; duplicateRow.Cells["column2"].Value = textBox1.Text; } 但现在它不再工作了,我怎样才能用更多的列做到这一点?
      • 我会建议你发布这个问题的新问题。包括您的最新代码,并描述它无法正常工作的原因。这将使提供帮助变得容易得多。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 2014-06-18
      • 2016-01-30
      相关资源
      最近更新 更多