如何根据两个DateTime列之间的计算差异为列分配值?

时间:2016-05-02 11:58:55

标签: c# datetime datagridview

如何将EventTimeCeaseTime列的值之间的差异分配到MTTR enter image description here列:

MTTR = EventTime - CeaseTime

我尝试使用数组,将string值转换为DateTime,但后来我不知道如何继续......

string[,] column0Array = new string[dataGridView1.Rows.Count,3];
int i = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    column0Array[i,1] = row.Cells[4].Value != null ? row.Cells[0].Value.ToString() : string.Empty;
    i++;
    column0Array[i,2] = row.Cells[5].Value != null ? row.Cells[0].Value.ToString() : string.Empty;
    i++;
}

这是添加MTTR列的按钮代码的一部分。

private void button3_Click(object sender, EventArgs e) 
{ 
    var MTTRColumn = new DataGridViewTextBoxColumn();
    MTTRColumn.Name = "MTTRColumn";
    MTTRColumn.HeaderText = "MTTR";
    MTTRColumn.ReadOnly = true;
    dataGridView1.Columns.Insert(5, MTTRColumn);
}

如何将EventTimeCeaseTime列的值之间的差异分配到MTTR列?

1 个答案:

答案 0 :(得分:1)

以下代码将执行您想要的操作:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    var val1= row.Cells[4].Value + "";

    var val2 = row.Cells[5].Value + "";

    DateTime dt1, dt2;//To store parsed values in dateTime variables

    // try to parse both values in columns
    if(DateTime.TryParse(val1, out dt1) &&
        DateTime.TryParse(val2, out dt2))
    {
        // both values are parsed successfully then assign    
        //computed result of two values in your MTTR column

        row.Cells["MTTR"].Value = (dt1 - dt2) + "";
    }
}

现在,当您通过评论提出新要求时,请考虑以下代码,这些代码可以在按钮点击时执行相同操作。

private void button1_Click(object sender, EventArgs e)
{
    if(dataGridView1.CurrentRow!-null)
    {
        var row = dataGridView1.CurrentRow;
        var val1= row.Cells[4].Value + "";                       
        var val2 = row.Cells[5].Value + "";

        DateTime dt1, dt2;//To store parsed values in dateTime variables

        // try to parse both values in columns
        if(DateTime.TryParse(val1, out dt1) &&
            DateTime.TryParse(val2, out dt2))
        {
            // both values are parsed successfully then assign    
            //computed result of two values in your MTTR column

            row.Cells["MTTR"].Value = (dt1 - dt2) + "";
        }
    }
}