Results 1 to 5 of 5

Thread: Try Catch Help

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Feb 2011
    Posts
    71

    Try Catch Help

    Hello all,

    I have a datagrid that I have coded to calculate fields by using code like this:

    Code:
    Me.DataGridView1.CurrentRow.Cells("Area").Value = _
            ((((Me.DataDataGridView1.CurrentRow.Cells("Diameter").Value) / 2) ^ 2) * 3.14)
    Can someone help me write a try/catch (or something better) that will not have an error if the user leaves the "Diameter" field blank or accidentally types something other than a number?

    I'd prefer if the field just stays blank and only calculates if there is a number typed into the field, otherwise show a message box if that's not possible.

    Any help greatly appreciated!

  2. #2
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,467

    Re: Try Catch Help

    vb Code:
    1. dim value as decimal
    2. if decimal.tryparse(Me.DataDataGridView1.CurrentRow.Cells("Diameter").Value,value) then
    3.     Me.DataGridView1.CurrentRow.Cells("Area").Value = _
    4.         (((value / 2) ^ 2) * 3.14)
    5. else
    6.     Me.DataGridView1.CurrentRow.Cells("Area").Value = ""
    7. end if

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Feb 2011
    Posts
    71

    Re: Try Catch Help

    I get the following error:

    Conversion from type 'DBNull' to type 'String' is not valid.

    Any thoughts? Thanks.

  4. #4
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,467

    Re: Try Catch Help

    Me.DataDataGridView1.CurrentRow.Cells("Diameter").Value.tostring

  5. #5

    Thread Starter
    Lively Member
    Join Date
    Feb 2011
    Posts
    71

    Re: Try Catch Help

    That way still gave me an error, just in a different way. I appreciate your help, it's very hard to try to figure out what people actually want without actually seeing the application first hand. In the dataset developer I set the field type to a string which quit giving me an error and this code I finally got to work by pure dumb luck:

    Code:
    If Not IsNumeric(Me.DataDataGridView1.CurrentRow.Cells("Diameter").Value) Then
                MsgBox("Diameter is not valid, please re-enter the diameter.")
            ElseIf Not IsDBNull(Me.DataDataGridView1.CurrentRow.Cells("Diameter").Value) Then
                Me.DataGridView1.CurrentRow.Cells("Area").Value = (((Me.DataGridView1.CurrentRow.Cells("Diameter").Value / 2) ^ 2) * 3.14)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width