Solved

Deal with Nullable Strings in ASP.NET VB.NET

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

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 63

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 63

Expert Comment

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

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

749 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