Reputation: 175
I Have Data Table which Contains Few row like below
CH1 CH2 Ch3 CH4 CH5
1 2 1 2 3
3 3 1 2 3
3 3 1 1 2
1 3 3 3 3
1 2 3 3 0
3 3 1 2 0
3 3 1 1 2
then I Try to add new column like
Dim col As New DataColumn("VCH1", GetType(Decimal),"(CH1+CH2+ch3)/CH5")
DtReadings.Columns.Add(col)
at that time give me error : Attempted to divide by zero. Because of CH5 have zero values, but I need to add Dynamic Column with different Expression at run time ,how to avoid such type of error any Idea please Help.
Expression value not fixed,User Create expression for dynamic Column. not only handle divide by zero error ,to handle all type of computing error
Upvotes: 1
Views: 1811
Reputation: 175
Simply Create One Extension for Solve my Problem,that's take a time but i have no problem
<Extension()>
Public Function ToCompute(value As DataTable, exp As String, inputColumn As String) As DataTable
Dim tempdt As New DataTable
tempdt = value.Clone
tempdt.Columns(inputColumn).Expression = exp
For Each row As DataRow In value.Rows.Cast(Of DataRow).ToList
Try
tempdt.Rows.Add(row.ItemArray)
value.Rows(value.Rows.IndexOf(row))(inputColumn) = tempdt.Rows(0)(inputColumn).ToString
tempdt.Rows.Clear()
Catch ex As Exception
tempdt.Rows.Clear()
value.Rows(value.Rows.IndexOf(row))(inputColumn) = 0
Continue For
End Try
Next
Return value
End Function
Upvotes: 0
Reputation: 216273
The Expression syntax allow the use of the IIF statement
You could build your DataColumn using this kind of syntax for the Expression
col = New DataColumn("VCH1", GetType(Decimal), "IIF(CH5 = 0, 0, (CH1+CH2+ch3)/CH5)")
Of course, being the Expression a string property you could build your expression dynamically based on the particular requirement you have at the moment. With IIF or ISNULL you could build your string on the fly before adding the column. Something like this pseudocode
Dim currentExpression as String = BuildCurrentExpression()
col = New DataColumn("VCH1", GetType(Decimal), currentExpression)
Upvotes: 1
Reputation: 9888
You can catch the DivideByZeroException
and then assign the value you want:
Try
col = New DataColumn("VCH1", GetType(Decimal), "(CH1+CH2+ch3)/CH5")
Catch ex As DivideByZeroException
col = New DataColumn("VCH1", GetType(Decimal), "0")
End Try
DtReadings.Columns.Add(col)
Upvotes: 1