我正在使用Visual Studio 2017.有一个带有文本框的窗体。这些文本框需要每10秒刷新一次。为了实现这一点,我使用了一个Timer事件。如何通过C#中的字符串访问EventHandler中的表单文本框?
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上的大多数结果都建议使用“查找方法”控件。
这与以前的尝试有什么不同当一个元素没有被找到而不是一个'IndexOutOfRangeException'时抛出一个'NullReferenceException'而不是OP? –
修复了NullReferenceException。 – Casperah