私はVisual Studio 2017を使用しています。テキストボックスのあるフォームがあります。これらのテキストボックスは、10秒ごとにリフレッシュする必要があります。これを達成するために、Timerイベントを使用します。EventHandler内のフォームテキストボックスにC#で文字列でアクセスする方法は?
public partial class status_window : Form
{
public status_window()
{
InitializeComponent();
shutdown_button.Click += new EventHandler(shutdown_click);
Timer timer = new Timer();
timer.Interval = (1 * 10000); // 10 secs
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
}
timer_tick関数は、status_windowクラスのメンバーです。そのイベントハンドラーの中で、私は期待どおりの名前でテキストボックスにアクセスできます。しかし、テキストボックス "アドレス"が私の変数である場合、それを行う方法。見てください:
private void timer_Tick(object sender, EventArgs e)
{
Int32 unixtime = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
// for all boxes per exname
for (int i = 0; i < something.Count() ; i++)
{
// try to find textbox 1 -> embty result
Console.WriteLine(this.Controls.Find("nam1_last_event", true));
Console.WriteLine(this.Controls.Find("nam2_last_event", true)); // also empty result
// this works and fills the formbox as ecxpected
nam1_last_event.Text = "somevalue";
nam1_event_count.Text = "anothervale";
nam2_last_event.Text = "somemorevalue";
nam2_event_count.Text = "andsoon";
// thats what i want later to use my for loop for those:
// something[i] exuals to nam1,nam2 and so on
this.Controls.Find(String.Format("{0}_last_event", something[i].ToLower()) , true)[0].Text = "somevalue"; // this fails cause array returned by find is empty
this.Controls.Find(String.Format("{0}_last_event", ex_name.ToLower()), true)[0].Text = "anothervale"; // same
}
}
私はここで何とか自分の知識によって制限されていました。 Googleの検索結果のほとんどは、コントロールの検索方法を使用することを提案しています。
これは、 OPが 'IndexOutOfRangeException'の代わりに要素が見つからないときに' NullReferenceException'を投げる以外の方法はありますか? –
NullReferenceExceptionが修正されました。 – Casperah