Solved

Deal with Nullable Strings in ASP.NET VB.NET

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

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

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

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…

622 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