0

私は以下のいくつかのコードを持っています:

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.Parameters.AddWithValue("@company", txtCompany.Text);
command.Parameters.AddWithValue("@server", txtServer.Text);
command.Parameters.AddWithValue("@username", txtUserName.Text);
command.Parameters.AddWithValue("@password", txtPassword.Text);

テキストボックスが常に入力されていることを確認して、空のテキストボックスを検証するにはどうすればよいですか?

私が試してみました:

if (string.IsNullOrEmpty(txtCompany.Text))

{
      //do work here
}

else
{

}

ただし、このようにすべてのテキスト ボックスを割り当てる方法がわかりません。私が書かなければならないコードの行数を制限するよりクリーンな方法で?

4

2 に答える 2

0

すべての textBoxes の TextBox_Validating を処理します。

public Form1()
{
    InitializeComponent();

    txtCompany.Validating += TextBox_Validating;
    txtServer.Validating  += TextBox_Validating;
    txtUserName.Validating  += TextBox_Validating;
    txtPassword.Validating  += TextBox_Validating;
}
private void TextBox_Validating(object sender, CancelEventArgs e)
{
    TextBox control = sender as TextBox;
    control.Focus();   
    e.Cancel = control.Text == string.Empty;
}

コマンドを実行する前に、次のコードを追加することもできます。

bool controlsAreValid = true;

foreach (Control control in this.Control)
{
   if (control is TextBox)
   {
      if (control.Text == string.Empty)
      {
          controlsAreValid = false;
          break;
      }
   }
}
if (!controlsAreValid)
     return;
于 2014-05-18T09:35:18.707 に答える