2017-08-24 30 views
0

我正在使用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上的大多數結果都建議使用「查找方法」控件。

回答

0

這個工作對我來說:

var inPanel = this.Controls.Find("inPanel", true).OfType<TextBox>().FirstOrDefault(); 
inPanel?.Text = "Found it"; 
+0

這與以前的嘗試有什麼不同當一個元素沒有被找到而不是一個'IndexOutOfRangeException'時拋出一個'NullReferenceException'而不是OP? –

+0

修復了NullReferenceException。 – Casperah

0

在您的代碼中,您同樣使用名稱nam1_last_event作爲類status_window的成員和控件的名稱。請檢查設計師您的控制繼電器是否有名稱nam1_last_event

功能Controls.Find使用作爲控制的屬性Name的值的鍵。

+0

你的意思是這一個? https://www2.pic-upload.de/img/33798040/Unbenannt.png – Steven

+0

不,這是隱藏在設計模式中的控制的單獨屬性。請查看文檔https://msdn.microsoft.com/en-us/library/system.windows.forms.control.name(v=vs.110).aspx – hsd

0

創建一個列表或字典變量來保存這些文本框,並將其獲取到timer_Tick中。

相關問題