Reputation: 1538
I am doing a Windows phone 8.1 project. In XAML, I have a two textboxes, one for first name and the other for last, and one button. In the button click event, i would like to display a message saying "blah blah blah" IF either (or both) of the textbox(es) is/are left empty.
I tried A LOT OF WAYS but haven't been able to get this. This is the best I could get, but it doesn't work in a way:
private async void Button_Click(object sender, RoutedEventArgs e) { if ((Textbox_first_name.DataContext== null) || (Textbox_last_name.DataContext== null)) { var dialog = new MessageDialog("message 2", "message 1"); await dialog.ShowAsync(); } else { Frame.Navigate(typeof(page3)); } }
With DataContext, i get the message to come up. But even if I enter anything, it doesn't take me to page 3. It just shows the message. So, it looks like it is not acknowledging the else block.
I tried
if ((Textbox_first_name_extractor.Text== null) || (Textbox_last_name_extractor.Text== null)) //same everything else
the message doesn't even come. It straight away takes me to the page three, even if it is empty. I don't know what I am doing wrong, or missing. Please help!
Windows 8.1; VS2013 Updt4;
Upvotes: 0
Views: 416
Reputation: 13642
You can access a TextBox's text through its Text
property and in this case validate it using String.IsNullOrEmpty
(or String.IsNullOrWhitespace, depending on your needs):
if (String.IsNullOrEmpty(Textbox_first_name) ||
String.IsNullOrEmpty(Textbox_last_name.Text))
{
var dialog = new MessageDialog("message 2", "message 1");
await dialog.ShowAsync();
}
Upvotes: 0
Reputation: 851
You could try:
if(String.IsNullOrWhiteSpace(Textbox_first_name_extractor.Text) ||
String.IsNullOrWhiteSpace(Textbox_last_name_extractor.Text))
as your if statement. This will check for null or empty/whitespace filled strings.
However, have you tried debugging your application? If so have you checked what the contents of .Text is for the two text boxes?
Alternatively, if you are using XAML, why not use databinding and validate against the bound properties?
Upvotes: 0