2017-03-04 38 views
0

假設我在一個表單上有100個文本框。數字進入這些文本框。C#添加表單中的所有文本框

我想要一個按鈕來點擊,它會放棄所有的空白文本框,並添加所有在它們中有數字的文本框。

我會怎麼做?

到目前爲止。這是我得到的代碼。我怎麼會把它加起來呢。

foreach (Control c in this.Controls) 
    { 
     if (c is TextBox) 
     { 
      TextBox textBox = c as TextBox; 
      if (textBox.Text != string.Empty) 
      { 
       //add! 
      } 
     } 
+4

[我有一個表格100個文本框(HTTP://i.stack。 imgur.com/fvdkb.png) – Plutonix

+0

我保證。這不是那樣的。根本!我是一個非常乾淨的用戶界面的堅定信徒。雖然,它看起來像。 –

回答

2

對於海量數據錄入,你應該考慮使用的DataGrid而不是TextBox - 因爲在的WinForms,這是,控件價格昂貴 - 它們是由User32管理的個體hWnd - 因此您的表單將會有些呆滯,並且重新繪製速度很慢本身如果所有100個文本框同時在屏幕上可見的話。

(事實上,你應該看看使用WPF構建你的UI,因爲它處理高DPI的更好,並使用「窗戶」硬件加速圖形)。

無論如何,你會想要一個樹遍歷函數來檢索所有的文本框,像@穆罕默德的答案,然後將其刪除。我注意到,您不能使用穆罕默德的直接回答,因爲當您通過控制訪問集合無法刪除的控制,所以試試這個:

public static IEnumerable<Control> GetDescendantControls(this Control control) 
{ 
    Stack<Control> stack = new Stack<Control>(); 
    stack.Push(control); 
    while(stack.Count > 0) 
    { 
     Control c = nodes.Pop(); 
     yield return c; 
     foreach(Control child in c.Controls) stack.Push(child); 
    } 
} 


List<Control> allEmptyTextBoxControls = this.GetDescendantControls() 
    .OfType<TextBox>() 
    .Where(c => String.IsNullOrWhitespace(c.Text)) 
    .ToList(); 

foreach(Control c in allEmptyTextBoxControls) c.Parent.Controls.Remove(c); 
0

要獲得所有控件

public static IEnumerable<TControl> GetChildControls<TControl>(this Control control) where TControl : Control 
{ 
    var children = (control.Controls != null) ? control.Controls.OfType<TControl>() : Enumerable.Empty<TControl>(); 
    return children.SelectMany(c => GetChildControls<TControl>(c)).Concat(children); 
} 

現在調用這個函數

var allTextBoxes = this.GetChildControls<TextBox>(); 
foreach (TextBox tb in allTextBoxes) 
{ 
    if(tb.Text != ""){ 
     //DO WHAT YOU WANT 
    } 
} 
+0

如果您刪除控件實例,則會在運行時崩潰,因爲集合在執行枚舉器內部將發生變化。你需要先將它們加載到一個臨時列表中(使用'ToList()')然後刪除它們。 – Dai

相關問題