VB.NET textbox default value 0

How to make a textbox if empty to a value 0 (zero)
Who is Participating?
CodeCruiserConnect With a Mentor Commented:
If you are using this in a calculation then you may want to use the IIF statement

Dim result As Integer = Integer.Parse(IIF(String.IsNullOrEmpty(txtA.Text), 0, txtA.Text)) + Integer.Parse(IIF(String.IsNullOrEmpty(txtB.Text), 0, txtB.Text))
If Len(txtName.Text) = 0 Then
    txtName.Text = "0"
End If

käµfm³d 👽Commented:
To add to jppinto's example, you may consider trimming the value before you test its length--in case the user entered all spaces.
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

HKH1967Author Commented:

i try it and it gives below error msg

Conversion from string "" to type 'Decimal' is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Conversion from string "" to type 'Decimal' is not valid.

Source Error:

Line 174:
Line 175:    Protected Sub txtDocAmount_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDocAmount.TextChanged
Line 176:        If CDec(txtAgentCommission.Text) = "" Then
Line 177:            txtAgentCommission.Text = "0"
Line 178:        End If

Source File: E:\Projects\NcbWork\Default.aspx.vb    Line: 176

let me know if I am wrong..
u want to make the textbox text as "0" when it is empy, right ?

why don u try this , its simple.

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        If TextBox1.Text = "".Trim Then

            TextBox1.Text = "0"

        End If
    End Sub

Open in new window

käµfm³d 👽Commented:

Is it not a bit redundant to trim an empty string literal  ; )


Why are you using CDec? You are trying to compare a decimal to a string. That doesn't make sense. Take another look at what jppinto posted  = )
i guess it should have been

   If TextBox1.Text.trim  = "" Then

OR simply

   If TextBox1.Text = "" Then
HKH1967Author Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.