Object, Control and array

时间:2017-12-18 06:26:39

标签: c# vb.net

I have the following code in VB.NET in which it will check for empty textboxes in an array. The code works fine but when I converted the code to C# it will no longer work. What do I miss? Please help.

Public Function CheckForEmptyTextBoxes(obj As Object()) As Boolean
    Dim QEmptyTextBox As Boolean
    For Each ctrl As Object In obj
        If TypeOf ctrl Is TextBox Then
            If CType(ctrl, TextBox).TextLength = 0 Then
                QEmptyTextBox = True
            Else
                QEmptyTextBox = False
            End If
        End If
    Next
    Return QEmptyTextBox
End Function

Code converted to C#

public bool CheckForEmptyTextBoxes(object[] obj)
 {
     bool QEmptyTextBox=false;
     foreach (object ctrl in obj)
     {
         if (ctrl is TextBox)
         {
             if ((TextBox)ctrl.TextLength == 0)
             {
                 QEmptyTextBox = true;
             }
             else
             {
                 QEmptyTextBox = false;
             }
         }
     }
     return QEmptyTextBox;
 }

1 个答案:

答案 0 :(得分:0)

You current code actually check if the last TextBox in the collection is empty:

     ...
     if (ctrl is TextBox)
     {
         if ((TextBox)ctrl.TextLength == 0)
         {
             QEmptyTextBox = true;  // <- please, notice absence of "break"
         }
         else
         {
             // this assigment can well overwrite empty TextBox found
             QEmptyTextBox = false; 
         }
     }
     ...

To amend your current code:

 public bool CheckForEmptyTextBoxes(object[] obj) {
   foreach (object ctrl in obj) {
     TextBox box = ctrl as TextBox;

     if ((box != null) && (string.IsNullOrEmpty(box.Text)))
       return true; // <- Empty TextBox found
   }  

   // We've scanned the entire collection and no empty TextBox has been found
   return false;
 }

If you want to check if there's at least one empty TextBox you can try Linq

using System.Linq;

...

public static bool CheckForEmptyTextBoxes(System.Collections.IEnumerable collection) {
  return collection
    .OfType<TextBox>()
    .Any(textBox => string.IsNullOrEmpty(textBox.Text));
}

...

if (CheckForEmptyTextBoxes(myPanel.Controls)) {
  // If there's an empty TextBox on myPanel 
}