Solved

Deal with Nullable Strings in ASP.NET VB.NET

Posted on 2016-09-18
5
36 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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
How do I get the id from URL? 19 48
work allocation; web development; vba; access; 4 46
XML & .net 5 21
Birthdays 3 14
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…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This video discusses moving either the default database or any database to a new volume.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

762 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