0

I am using the following code to try to set the Textbox value as 0 when textbox1.text ="".

if(textbox1.text=="")
{
     int.Parse(textbox1.Text) == 0.ToString();
}

However I recieve the following error:

Error: CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement.

How do I set the textbox value to 0 in C#?

6 Answers 6

4

A simple assignment operator should do the job. You really don't need to do any parsing and equality comparison operator:

if(textbox1.Text == "")
{
    textbox1.Text = "0";
}
Sign up to request clarification or add additional context in comments.

1 Comment

This error must be somewhere else. In a portion of the code that you haven't shown.
1

you are parsing the value of the TextBox to integer ,but you don't want to do that ,you want to set it's value, so simply use the setter property

yourTextBox.Text="0";

and then you are setting it wrong using the conditional == instead of the assignment =

== is used to check if two things are equal ex: 1==1

you should use this = to assign or set

Comments

1

Solution for your problem

if (string.IsNullorEmpty(textbox1.Text))
{
    textbox1.Text = "0";
}

Reasons for your problem

  1. int.Parse returns an integer and you are trying to compare string to int.
  2. == operator is used to check whether left hand side is equal to right hand side, which you are trying to use as an assignment operator.

1 Comment

+1 for NullOrEmpty - No idea why someone downvoted this, it looks to be a good answer to me.
0
if(String.IsNullOrEmpty(textbox1.Text))
{
     textbox1.Text = "0";
}

IsNullOrEmpty wud check for null values also.

Comments

0

There are couple of things wrong with the code.

int.Parse if its able to parse will give a int value while you have set up a comparison of the same with a string.

Next you can use string.IsNullOrEmpty to check if the TextBox is empty or not.

Finally you can just assign "0" as string to the .Text property of the TextBox

if(String.IsNullOrEmpty(textbox1.Text))
{
     textbox1.Text = "0";
}

Comments

-1

Try to use this:

if(textbox1.Text == "")
{
    textbox1.Text = "0";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.