Write Null in Database if the TextBoxes are Empty
-
13-07-2021 - |
Pergunta
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
Solução
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
Outras dicas
Consider something lighter than a new method :
Cmd.Parameters.AddWithValue("@AccntID", IIF(String.IsNullOrEmpty(TextBox1.Text), DBNull.Value, TextBox1.Text))
But for the rest, use a SqlDataAdapter
as suggested before.
The best way will be to inherited text box and add additional functionality to it
Public Class MyText
Inherits TextBox
'Either change default text property (but this will bug you while comparing text property)
Public Overrides Property Text() As String
Get
Return MyBase.Text
End Get
Set(ByVal value As String)
MyBase.Text = value
End Set
End Property
'Best way will be to write new property to use in sql query
Public ReadOnly Property TextSQL() As String
Get
If Me.Text = String.Empty Then
Return "NULL"
Else
Return Me.Text
'Return "'" & Me.Text & "'" 'or this
End If
End Get
End Property
End Class
now use this text box in your application
cmd.Parameters.AddWithValue("@accountholder", txt_accHolder.TextSQL)
In the stored procedure you can use following:
Assumption: parameter name is @TextData
NULLIF(LTRIM(RTRIM(@TextData)),'')
It will return NULL if @TextData = ''.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow