1

Aim: I want to check if the value is Null and it is then add blank otherwise add data

Issue: I am unsure on what I need to put after the first comma to change the Null to "" and also then if it actually has data to import that instead

    With commandSQL
    .Connection = connection
    .CommandText = "spAddCSVDataLine"  'Stored procedure here
    .CommandType = CommandType.StoredProcedure
    .Parameters.AddWithValue("Name", (IsDBNull(ds.Tables("dataExcel").Rows(j)("Name"))),"",Trim(ds.Tables("dataExcel").Rows(j)("Name"))))

I can do the following but I would like to tighten the code up onto one line if possible:

If IsDBNull(ds.Tables("dataExcel").Rows(j)("Name")) Then
.Parameters.AddWithValue("Name", "")
Else
.Parameters.AddWithValue("Name", Trim(ds.Tables("dataExcel").Rows(j)("Name")))
End If
Jon Senchyna
  • 7,867
  • 2
  • 26
  • 46
indofraiser
  • 1,014
  • 3
  • 18
  • 50

2 Answers2

3
Dim row = ds.Tables("dataExcel").Rows(j)

.Parameters.AddWithValue("@Name", If(row.IsNull("Name"), String.Empty, CStr(row("Name"))))
ekad
  • 14,436
  • 26
  • 44
  • 46
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
3

I think you're looking for the If operator:

With commandSQL
    .Connection = connection
    .CommandText = "spAddCSVDataLine"  'Stored procedure here
    .CommandType = CommandType.StoredProcedure
    .Parameters.AddWithValue("Name", If(IsDBNull(ds.Tables("dataExcel").Rows(j)("Name")), "", Trim(ds.Tables("dataExcel").Rows(j)("Name"))))
End With
ekad
  • 14,436
  • 26
  • 44
  • 46
Aaron Palmer
  • 8,912
  • 9
  • 48
  • 77
  • Isn't inline If `IIF`? – Obsidian Phoenix Feb 07 '14 at 12:50
  • That's If operator, not If statement. – jmcilhinney Feb 07 '14 at 12:51
  • @Obsidian Phoenix, no IIf is a method that has been included in VB.NET since the first version. The If operator was added in VB 2008 I think it was. Because it is an operator and not a method, it is able to short-circuit, i.e. it only evaluates the third operand if it's needed, just as the C# ternary ?: operator does. – jmcilhinney Feb 07 '14 at 12:54
  • @AaronPalmer huh, learn something new every day. I tend to avoid `IIF` in general, but was unaware of using `IF` inline. – Obsidian Phoenix Feb 07 '14 at 12:54