none
Avoid using Try Catch in a Loop to Handle Errors RRS feed

  • Question

  • Hi,

    I have a Datagridview full of data, i'm reading a particular column in order to change its color based on it value (a date), but since that date will not be always available it will cause an error eventually (more than once depending on Row count).

    So far i tried Try Catch block but its causing me a big performance impact when using it.

    Is there a way to skip using Try Catch blocks? i understand that Try Catch is not good for such a repetitive error like this.

    I need a way to skip this command of coloring if no data is available yet.

    Thanks in advance,

    Adrian.

                DateTime Today = Convert.ToDateTime(DateTime.Now.ToShortDateStri.ng());
                DateTime? Need; // Used ? in order to set it as Null when data is empty
                foreach (DataGridViewRow R in Current.Rows)
                {
                    try
                    {
                        Need = Convert.ToDateTime(R.Cells[12].Value);
                    }
                    catch (Exception error)
                    {
                        Need = null;
                    }
                    if (Need < Today)
                    {
                        R.Cells[0].Style.BackColor = Color.MistyRose; // so on for every column
                    }
                    Need = null;
                }

    Tuesday, March 5, 2019 6:36 PM

Answers

  • Hello,

    Look at DateTime.TryParse. There are examples on the page.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by Adrianstorm92 Tuesday, March 5, 2019 8:14 PM
    Tuesday, March 5, 2019 6:59 PM
    Moderator

All replies

  • Hello,

    Look at DateTime.TryParse. There are examples on the page.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by Adrianstorm92 Tuesday, March 5, 2019 8:14 PM
    Tuesday, March 5, 2019 6:59 PM
    Moderator
  • Hi

    foreach (DataGridViewRow Myrow in dataGridView1.Rows)
                {
                 
                    if (int.Parse(Myrow.Cells[5].Value.ToString()) != 0)
                    {
                        Myrow.DefaultCellStyle.BackColor = Color.Green;
                      
                    }
                    else
                    {
                       
                        Myrow.Cells[4].Style.ForeColor = Color.Red;
                    }
                    i++;
                }

    //-------------------------

       public static void Main()
     {
      System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
      // Defining Format
      string format = "MM/dd/yyyy HH:mm:ss tt";
      string dtNow  = DateTime.Now.ToString (format);
      Console.WriteLine ("Date Time Now : " + dtNow);
      
      // Trying to Parse DateTime
      DateTime time;
      if (DateTime.TryParseExact (dtNow, format, provider, System.Globalization.DateTimeStyles.None, out time))
      {
       // If TryParseExact Worked
       Console.WriteLine ("Result: " + time.ToString ()); 
      }
      else
      {
       // If TryParseExact Failed
       Console.WriteLine ("Failed to Parse Date");
      }
      // Trying to use method with higher tolerance
      ParseDate ("03/05/2019 10:00:00 PM", new String[] {format}, out time);
      Console.WriteLine (time);
     }

    public static void ParseDate (string value, string[] masks, out DateTime result)
     { 
      DateTime.TryParseExact(value, masks,
       System.Globalization.CultureInfo.InvariantCulture,
       System.Globalization.DateTimeStyles.AssumeUniversal
       | System.Globalization.DateTimeStyles.AdjustToUniversal
       | System.Globalization.DateTimeStyles.AllowInnerWhite
       | System.Globalization.DateTimeStyles.AllowLeadingWhite
       | System.Globalization.DateTimeStyles.AllowTrailingWhite,
        out result);
     }
    }

    Best regards.

    Please click the Mark as answer button and vote as helpful if this reply solves your problem.



    Tuesday, March 5, 2019 7:35 PM
  • Thanks a lot Karen,

    Although i used DateTime.TryParse i still had errors, i manage caught my own additional mistake thank to this.

    My error was that i was trying to convert to Date something empty (i.e " "), so now i'm reading the actual string and checking with DateTime.TryParse if its a valid date.

                DateTime Today = Convert.ToDateTime(DateTime.Now.ToShortDateString());
                string DateString;
                DateTime Need;
    
                foreach (DataGridViewRow R in Current.Rows)
                {
                    DateString = (R.Cells[12].Value).ToString();
                    //NeedCheck = DateTime.TryParse(Convert.ToDateTime(R.Cells[12].Value).ToString(),out DateTime Need);
                    if (DateTime.TryParse(DateString, out Need)) // Actual Date in correct format is entered
                    {
                        if (Need < Today)
                        {
                           //Does painting
                        }
                    }
                }
    
    
    


    Tuesday, March 5, 2019 8:20 PM