Search code examples
asp.netsql-servervb.netado.netdbnull

Write Null in Database if the TextBoxes are Empty


All I want to do is to insert Null with the database when the textbox is empty.

 --ACCOUNT

 AS
 BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SET IDENTITY_INSERT account ON


  INSERT INTO dbo.account
      ( 
        AccntID                   ,
        managedby                 ,
        AccountHolder             ,
        Description               ,
        AccountType               ,
        ContactPerson             ,
        ContactNumber             ,
        EmailAddress              ,
        Address                   ,
        ClientTYpe                ,
        SchemeType                ,
        SalesManager              ,
        DateCreated               ,
        Login                     ,
        Password                  ,
        Balance                   ,
        FilterOption              ,
        Enable22                  ,
        AllowExtendedConfig                  
      ) 
-- Insert statements for procedure here

 VALUES (@AccntID, @managedby, @AccountHolder, @Description, @AccountType, @ContactPerson, @ContactNumber, @EmailAddress, @Address, @ClientType, @SchemeType, @SalesManager, @DateCreated, @Login, @Password, @Balance, @FilterOption, @Enable22, @AllowExtendedConfig)
SET IDENTITY_INSERT account OFF



END

What is the best way to add NULL values to the database when my textboxes are empty


Solution

  • Set up helper functions such as:

    Public Function DbNullOrStringValue(ByVal value As String) As Object
        If String.IsNullOrEmpty(value) Then
            Return DBNull.Value
        Else
            Return value
        End If
    End Function
    

    And so the first code block would be simplified by calling it thus:

    Cmd.Parameters.AddWithValue("@AccntID", DbNullOrStringValue(TextBox1.Text)) 
    Cmd.Parameters.AddWithValue("@managedby", DbNullOrStringValue(TextBox2.Text)) 
    Cmd.Parameters.AddWithValue("@AccountHolder", DbNullOrStringValue(TextBox3.Text)) 
    Cmd.Parameters.AddWithValue("@Description", DbNullOrStringValue(TextBox4.Text)) 
    Cmd.Parameters.AddWithValue("@AccountType", DbNullOrStringValue(TextBox5.Text))
    

    Cmd is your SqlCommanad object