VB.NET textbox default value 0

How to make a textbox if empty to a value 0 (zero)
HKH1967Asked:
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))
0
 
jppintoCommented:
If Len(txtName.Text) = 0 Then
    txtName.Text = "0"
End If

0
 
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.
0
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:
ippinto:

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

0
 
bilal_fazlaniCommented:
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

0
 
käµfm³d 👽Commented:
@bilal_fazlani

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

@HKH1967

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  = )
0
 
bilal_fazlaniCommented:
ohhhh...yeah
i guess it should have been

   If TextBox1.Text.trim  = "" Then

OR simply

   If TextBox1.Text = "" Then
0
 
HKH1967Author Commented:
thanks
0
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.