/ /オブジェクト、コントロール、配列[終了] - c#、vb.net

オブジェクト、コントロール、配列[closed] - c#、vb.net

私はそれが配列内の空のテキストボックスをチェックする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;
}

回答:

回答№1は0

現在のコードは実際に 最終 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
}