ユーザーが textBox1 に 3 文字未満しか入力しない場合、IndexOutOfRange エラーを防ぐにはどうすればよいですか?
を使用して確認してくださいtemp.Length
:
if (temp.Length > 0)
{
...
}
... またはswitch
/を使用しますcase
。
また、配列はまったく必要ありません。ToString
各文字を呼び出すか、次を使用しSubstring
ます。
string temp = textBox1.Text;
switch (temp.Length)
{
case 0:
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
break;
case 1:
// Via the indexer...
textBox2.Text = temp[0].ToString();
textBox3.Text = "";
textBox4.Text = "";
break;
case 2:
// Via Substring
textBox2.Text = temp.Substring(0, 1);
textBox3.Text = temp.Substring(1, 1);
textBox4.Text = "";
break;
default:
textBox2.Text = temp.Substring(0, 1);
textBox3.Text = temp.Substring(1, 1);
textBox4.Text = temp.Substring(2, 1);
break;
}
もう 1 つのオプション (さらに優れた方法) は、条件演算子を使用することです。
string temp = textBox1.Text;
textBox2.Text = temp.Length < 1 ? "" : temp.Substring(0, 1);
textBox3.Text = temp.Length < 2 ? "" : temp.Substring(1, 1);
textBox4.Text = temp.Length < 3 ? "" : temp.Substring(2, 1);