Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
with each click the price from textbox should add to list view and then the textbox will be cleared at the end and here is my problem if i press the button when textbox is empty it will add the null value to listview without considering the condition inside the if loop

What I have tried:

C#
if (tbBar1price.Text!=null)
            {
                lvBar1.Items.Add(tbBar1price.Text);
                tbBar1.Clear();
            }
Posted
Updated 28-Mar-20 5:17am

1 solution

The TextBox.Text property is a string, and will never return a null value - even for an "empty" TextBox - instead it returns an empty string: either "" or string.Empty (they are the same thing and can be used interchangeably).

So instead of testing for null, check for an empty TextBox. The best way to do that is like this:
C#
if (!string.IsNullOrWhiteSpace(tbBar1price.Text))
   {
   ...
As that allows the user to enter spaces without accepting those, either.

It's probably a good idea to check the values when the user enters them though: if he enters "hello" as the price, you don't want that getting into your database as it'll only mess up later processing and you can't easily correct it once entered.
Look at the various TryParse methods to convert the user input to a number:
Int32.TryParse Method (System) | Microsoft Docs[^]
Double.TryParse Method (System) | Microsoft Docs[^]
for example.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900