2016-08-12 55 views
2

我想在提交數據後清除C#中Windows窗體的內容。我提交表單後,如何清除「組合框」的內容

我已成功地使用下面的代碼文本框做到這一點:

foreach (Control c in Controls) 
{ 
    if (c is TextBox) 
    { 
     c.Text = ""; 

不過,我奮力完成相同任務表單內的「組合框」。我試圖如下使用代碼的變體,但這似乎不起作用。

if (c is ComboBox) 
{ 
    c.Text = ""; 

所以完整的代碼如下所示:

foreach (Control c in Controls) 
{ 
    if (c is TextBox) 
    { 
     c.Text = ""; 
    } 
    if (c is ComboBox) 
    { 
     c.Text = ""; 
    } 

任何人都可以建議一個解決方案,我缺少什麼?

親切的問候

伊恩

+6

使用'comboBox.Items.Clear();' –

+0

你在談論的WinForms組合框或?你如何在代碼的開頭填充組合?這是要求告訴你清除組合項目的有效方法 – Steve

+0

是的WinForms組合框和下拉樣式是「DropDownList」。 –

回答

1

你的代碼是這樣的:

//your submission of the form code here... 

foreach (Control c in this.Controls) 
{ 
    if (c is TextBox) 
    {      
     ((TextBox)c).Clear(); 
     //c.Text = String.Empty; 
    } 
    if (c is ComboBox) 
    { 
     ((ComboBox)c).Items.Clear(); 
    } 
} 
+1

非常感謝Rakitic,你的建議完美無缺! –

2

嘗試

if (c is ComboBox) 
{ 
    c.Items.Clear(); 
} 
1

例如說要清除所有的文本框,你可以做這樣的事情

YourForm.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear()); 

對於ComboBox你可以做同樣的事情

YourForm.Controls.OfType<ComboBox>().ToList().ForEach(comboBox => comboBox.Items.Clear());