我在VB.NET中有以下代码,它将检查数组中的空文本框。代码工作正常但是当我将代码转换为C#时它将不再有效。我错过了什么?请帮忙。
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
代码转换为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;
}
您当前的代码实际检查集合中的最后一个TextBox
是否为空:
...
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;
}
}
...
要修改您当前的代码:
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;
}
如果你想检查是否至少有一个空的TextBox
你可以尝试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
}