-1

したがって、mysqlクエリを返す次の文字列がc#にあります。

string id = cmd.ExecuteScalar().ToString();

問題は、この文字列への入力が有効でない場合、アプリがクラッシュすることです。これによりアプリがクラッシュすることはありませんが、次のように表示されます。

MessageBox.Show("Your key (" + KeyNr + ") was invalid or not active. \nPlease check if it is the correct key or you need to buy another month.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

トライアンドキャッチで試してみましたが、うまくいきませんでした。誰かが助けることができますか?

私の試みのいくつか:

try
{
   string id = cmd.ExecuteScalar().ToString();
}
catch (Exception ex)
{
   MessageBox.Show("Your key (" + KeyNr + ") was invalid or not active. \nPlease check if it is the correct key or you need to buy another month.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

try
{
   string id = cmd.ExecuteScalar().ToString();
}
catch (catch (MySqlException))
{
   MessageBox.Show("Your key (" + KeyNr + ") was invalid or not active. \nPlease check if it is the correct key or you need to buy another month.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

すべてが私に与えます:

Error   2   The name 'id' does not exist in the current context
4

2 に答える 2

4

cmd.ExecuteScalar()それを解決せずに、実行されて文字列に変換できると想定する前に、結果を保存して確認する必要があります。

var result = cmd.ExecuteScalar();
if (/* result is valid */){
  id = result.ToString();
} else {
  MessageBox.Show(/* message */);
}

例外チェックを使用することはパフォーマンスに不必要に重く、(多くの点で)古き良きチェックをスキップする怠惰な方法であるため、可能な限り例外チェックを避けてください。

于 2012-10-28T18:43:26.187 に答える
0

このコードを試してください:

string id = string.Empty;

try
{
   id = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
    MessageBox.Show("Your key (" + KeyNr + ") was invalid or not active. \nPlease check if it is the correct key or you need to buy another month.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

ジェネリックを使用する代わりに、より具体的な例外をキャッチすることもできますException

于 2012-10-28T18:42:26.923 に答える