Solved

Deal with Nullable Strings in ASP.NET VB.NET

Posted on 2016-09-18
5
44 Views
Last Modified: 2016-09-19
I just learned - thanks to Fernando Soto - how to deal with empty Integers when saving data to SQL from an unbounded Field in my webpage. How do I do the same with Strings so that in SQL if will have a NULL value when my BoxMyText is Empty? Right now I see a blanc column but I don't see the word NULL in it so I think I may be saving a blanc space of something like that.

Protected Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim MyText As String
Dim Filed1 As Nullable(Of Integer)
Dim Field2 As Nullable(Of Integer)

Using con As SqlConnection = GetSqlConnection()

If Not String.IsNullOrWhiteSpace(BoxMyText .Text) Then
    MyText = BoxMyText.Text
Else
    MyText = ""
End If

If (Not String.IsNullOrWhiteSpace(BoxFiled1.Text)) AndAlso IsNumeric(BoxFiled1.Text) AndAlso Filed1.Text > 0 Then
     Filed1 = Integer.Parse(BoxFiled1.Text)
 Else
      Filed1 = Nothing
 End If
...

Save(con, Field1, Field2, MyText)
End Using

Private Sub Save(con As SqlConnection, Field1 As Nullable(Of Integer), Field2 As Nullable(Of Integer), MyText As String)
        Using cmd As New System.Data.SqlClient.SqlCommand
            cmd.CommandType = System.Data.CommandType.Text
            cmd.CommandText = "INSERT INTO MYTABLE(Field1, Field2 , MyText ) " &
                "VALUES (@Field1, @Field2, @MyText);"
            cmd.Connection = con
            cmd.Parameters.AddWithValue("@Field1", If(Field1.HasValue, Field1.Value, DBNull.Value))
            cmd.Parameters.AddWithValue("@Field2", If(Field2.HasValue, Field2.Value, DBNull.Value))
            cmd.Parameters.AddWithValue("@MyText ", MyText)
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using

Private Shared Function GetSqlConnection() As SqlConnection
        Dim constring As String = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
        Dim con As New SqlConnection(constring)
        Return con
End Function

Open in new window

0
Comment
Question by:Cobra967
  • 3
  • 2
5 Comments
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 41804026
Hi Cobra967;

I am sorry I thought that it was totally different. Basically it is the same as the Nullable(Of Integer) but with strings it is Nullable(Of String). I have modified the code you posted to show what needs to be modified.
Protected Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim MyText As Nullable(Of String)
Dim Filed1 As Nullable(Of Integer)
Dim Field2 As Nullable(Of Integer)

Using con As SqlConnection = GetSqlConnection()

If Not String.IsNullOrWhiteSpace(BoxMyText.Text) Then
    MyText = BoxMyText.Text
Else
    MyText = Nothing
End If

If (Not String.IsNullOrWhiteSpace(BoxFiled1.Text)) AndAlso IsNumeric(BoxFiled1.Text) AndAlso Filed1.Text > 0 Then
     Filed1 = Integer.Parse(BoxFiled1.Text)
 Else
      Filed1 = Nothing
 End If
...

Save(con, Field1, Field2, MyText)
End Using

Private Sub Save(con As SqlConnection, Field1 As Nullable(Of Integer), Field2 As Nullable(Of Integer), MyText As Nullable(Of String))
        Using cmd As New System.Data.SqlClient.SqlCommand
            cmd.CommandType = System.Data.CommandType.Text
            cmd.CommandText = "INSERT INTO MYTABLE(Field1, Field2 , MyText ) " &
                "VALUES (@Field1, @Field2, @MyText);"
            cmd.Connection = con
            cmd.Parameters.AddWithValue("@Field1", If(Field1.HasValue, Field1.Value, DBNull.Value))
            cmd.Parameters.AddWithValue("@Field2", If(Field2.HasValue, Field2.Value, DBNull.Value))
            cmd.Parameters.AddWithValue("@MyText ", If(MyText.HasValue, MyText.Value, DBNull.Value))
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using

Private Shared Function GetSqlConnection() As SqlConnection
        Dim constring As String = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
        Dim con As New SqlConnection(constring)
        Return con
End Function

Open in new window

0
 

Author Comment

by:Cobra967
ID: 41804063
I did your suggestion before asking you Fernando, however it does not work for me (as usual).

This is what I get:
Line 2: First, Studio underline in red the word 'String' saying that it can be simplified as 'Dim MyText As String?' (No quotations)
Then, after change it (or not) I get: Type 'String' must be a value type or a type argument constrained to in order to be used with or nullable modifier '?'.

Line 9: Value of type 'String' cannot be converted to 'String?'

Line 24: Type 'String' must be a value type or a type argument constrained to in order to be used with or nullable modifier '?'.
0
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 41804098
Sorry about that my error. A String data type is a reference type and therefore can be set to Nothing / Null and therefore no need to use Nullable type. I have gone through the code and re-modified, hopefully correctly. Look for comments in code for where I made changes.
Protected Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
'' Made the data type back to string
Dim MyText As String
Dim Filed1 As Nullable(Of Integer)
Dim Field2 As Nullable(Of Integer)

Using con As SqlConnection = GetSqlConnection()

If Not String.IsNullOrWhiteSpace(BoxMyText.Text) Then
    MyText = BoxMyText.Text
Else
    MyText = Nothing
End If

If (Not String.IsNullOrWhiteSpace(BoxFiled1.Text)) AndAlso IsNumeric(BoxFiled1.Text) AndAlso Filed1.Text > 0 Then
     Filed1 = Integer.Parse(BoxFiled1.Text)
Else
      Filed1 = Nothing
End If
...

Save(con, Field1, Field2, MyText)
End Using

'' Made change to last parameter on next line
Private Sub Save(con As SqlConnection, Field1 As Nullable(Of Integer), Field2 As Nullable(Of Integer), MyText As String)
        Using cmd As New System.Data.SqlClient.SqlCommand
            cmd.CommandType = System.Data.CommandType.Text
            cmd.CommandText = "INSERT INTO MYTABLE(Field1, Field2 , MyText ) " &
                "VALUES (@Field1, @Field2, @MyText);"
            cmd.Connection = con
            cmd.Parameters.AddWithValue("@Field1", If(Field1.HasValue, Field1.Value, DBNull.Value))
            cmd.Parameters.AddWithValue("@Field2", If(Field2.HasValue, Field2.Value, DBNull.Value))
            '' Made change here
            cmd.Parameters.AddWithValue("@MyText ", If(String.IsNullOrWhiteSpace(MyText), MyText, DBNull.Value))
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using

Private Shared Function GetSqlConnection() As SqlConnection
        Dim constring As String = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
        Dim con As New SqlConnection(constring)
        Return con
End Function

Open in new window

0
 

Author Closing Comment

by:Cobra967
ID: 41804145
Thank you Fernando, once again YOU did it! Its works like a charm. Thank you very much.
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 41804578
Not a problem Cobra967, glad to help.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
A short film showing how OnPage and Connectwise integration works.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

948 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now