Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Deal with Nullable Strings in ASP.NET VB.NET

Posted on 2016-09-18
5
Medium Priority
?
74 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 64

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 64

Accepted Solution

by:
Fernando Soto earned 2000 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 64

Expert Comment

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

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

670 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