2017-05-04 43 views
2

我有一個數據網格,其中的時間值列如0:15,0:30,0:45,1:00。將字符串單元格值轉換爲秒

當row.Cells [2]字符串的值高於1:00,所以它的3600時,我想將背色變爲紅色。我想我需要將它轉換爲秒,然後檢查它是否高於searchValue。我設法檢查是否平等,但我不知道如何將其轉換爲秒,然後檢查它是否更高。

 SqlDataAdapter asdf; 
     DataTable ss; 
     asdf = new SqlDataAdapter("SELECT Firma, Czas, Opis,ID FROM Rok2016 WHERE [email protected] AND [email protected]", con); 
     asdf.SelectCommand.Parameters.AddWithValue("@DT", monthCalendar1.SelectionRange.Start.Date); 
     asdf.SelectCommand.Parameters.AddWithValue("@Kto", label3.Text); 
     ss = new DataTable(); 

     asdf.Fill(ss); 
     dataGridView1.DataSource = ss; 

     String searchValue = "3600"; 
     foreach (DataGridViewRow row in dataGridView1.Rows) 



     if (row.Cells[2].Value.ToString().Equals(searchValue)) 

      { 

       row.DefaultCellStyle.BackColor = Color.Red; 
      } 

回答

0

如果row.Cells[2].Value.ToString()返回「00:15」或另一數量,比如「1點14」或「15時53分」,則可以將其分離成小時和分鐘值的陣列,解析它爲int (searchValueInSecondsString爲好),將其轉換爲時間跨度,讓所有的總秒數和最終你可以comparse它,就像下面的例子:

String searchValueInSecondsString = "3600"; 

foreach (DataGridViewRow row in dataGridView1.Rows) 
{ 
    var separateHourAndMinutes = row.Cells[2].Value.ToString().Split(':'); 

    // safety first! ;) 
    if (separateHourAndMinutes.Length != 2) 
    { 
     Console.WriteLine("Wrong time value from grid!"); 
    } 
    else 
    { 
     // safety second! ;) 
     if (int.TryParse(separateHourAndMinutes[0], out var hours) && int.TryParse(separateHourAndMinutes[1], out var minutes) && int.TryParse(searchValueInSecondsString, out var searchValue)) 
     { 
      // if you want to make something red, if the search value and the time value are higher and equal, use >= instead of > 
      if (new TimeSpan(hours, minutes, 0).TotalSeconds > searchValue) 
      { 
       Console.WriteLine("I make it red!"); 
      } 
     } 
    } 
} 

請注意,我已經改變了名稱searchValue到searchValueInSecondsString,要知道搜索值需要什麼輸入(秒和字符串)

PS:如果你想玩點代碼點擊:https://dotnetfiddle.net/1OVfDy

+0

row.Cells [2] .Value.ToString()返回00:15 00:30等我輸入3600,因爲我認爲我必須以某種方式轉換00:15秒,然後比較它到小時 –

+0

我已更新我的答案。這應該適合你。除了功能外,我還增加了一些安全功能。 –