Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Dear Friends,

I have two textboxes like TextBox1 & TextBox2. Now whenever click to submit button i want error alter message if both textboxes are empty, if either one textbox data is fill it shows successfull message.


Note: I need data at least one textbox either TextBox1 or TextBox2 or both by using C# code?


Thanks in advanced.
Posted
Comments
Sergey Alexandrovich Kryukov 6-Aug-14 2:28am    
To start with: what your text box class? Or what is the application type and UI library used?
—SA
Sergey Alexandrovich Kryukov 6-Aug-14 2:51am    
By the way, you formally accepted a totally incorrect answer; it will give you wrong result if one text box is empty and another is not. Don't use this false "solution". There is a button to cancel your acceptance.
—SA

Here is the thing to take into account: a text box value is never null but can be empty.

So, for the two, a very short line to check would be
C#
if (TextBox1.Text + TextBox2.Text != string.Empty) //...

However, it's possible that your requirement is not having non-empty text, but also not having the text consisting only of the blank space characters. If so, the check could be improved with a bit more complex on-liner:
C#
if (TextBox1.Text.Trim() + TextBox2.Text.Trim() != string.Empty) //...


One note: never ever use auto-generated names like TextBox1 or TextBox2; they violate (good) Microsoft naming conventions and are not really intended for permanent use; you need to rename all such name to correct semantically sensible names using correct English spelling. It will greatly improve maintainability of your code.

—SA
 
Share this answer
 
v2
Comments
CPallini 6-Aug-14 2:46am    
Very good. 5.
Sergey Alexandrovich Kryukov 6-Aug-14 2:49am    
Thank you, Carlo.
—SA
Hello



Write below code on submit button click event.


if(string.IsNullOrEmpty(TextBox1.Text) && string.IsNullOrEmpty(TextBox2.Text))
{
MessageBox.Show("Error");
}
else
{
//Do you code here
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 6-Aug-14 2:29am    
There is no need to check for null: text box value is never null. It's enough to check for empty.
Please see my answer.

Besides, your code gives incorrect result. If you read OP's requirements, you would check if at least one of the text boxes would be non-empty. Instead, you check if both text boxes are non-empty. This kid's logical mistake well deserves my vote of 1, sorry.

—SA

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