Visual C#2010でWindowsフォームアプリケーションを作成しています。
button1、...、button20という名前の20個のボタンと、label1、...、label20という名前の20個のラベルがあります。button1のクリックに応じてlabel1のテキストを変更するにはどうすればよいですか。同様に、20個の個別のイベントハンドラー関数を使用せずに、各ボタンとラベルのペアで変更できますか?
For the love of god why!!!
But really you could use a dictionary keyed to the button, for example:
Dictionary<Button,Label> dict = new Dictionary<Button,Label>();
dict.Add(button1,label1);
...
Then you can just do:
private void ButtonClick(object sender, EventArgs e)
{
Label label = dict[(Button)sender];
label.Text = "Hello";
}
All buttons can then use the same click handler.
You could also similarly use Button.Tag
and have that point to each label.
However, I think the better solution would be to develop a custom UserControl that shrink wraps your button and label into one neat package.
コントロールのグループを何度も使用する場合は、それらをまとめたカスタム ユーザー コントロールを作成する方が簡単です。
したがって、この場合は、ラベルとボタンを持つ新しいユーザー コントロールを作成します。ボタンの onclick ハンドラーで、label.Text を希望するものに変更します。プロジェクトをビルドします。
新しく作成したユーザー コントロールをメイン フォームに 20 回追加します。ボタンはそれぞれのラベルに既に関連付けられているため、ボタンごとに個別のハンドラーを用意する必要はありません。
(現在、userControl1、userControl2 などの名前の 20 個のコントロールがあることに注意してください。そのため、内部コンテンツで何か他のことを行う必要がある場合は、追加の処理を行う必要があります。ただし、この例のために、これは気にしなくていいです。)
You can subscribe all events to one handler and check first argument 'sender'. Sender should be the button, you can check its ID.