提交表单后如何清除“comboBox”的内容

时间:2016-08-12 19:38:19

标签: c# foreach combobox

我在提交数据后试图在C#中清除Windows窗体的内容。

我已设法使用以下代码为文本框执行此操作:

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

但是,我正在努力为表单中的“组合框”完成相同的任务。我试图使用如下代码的变体,但这似乎不起作用。

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

所以完整代码如下所示:

{{1}}

任何人都可以建议解决方案,我缺少什么?

亲切的问候

伊恩

3 个答案:

答案 0 :(得分:2)

尝试

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

答案 1 :(得分:1)

例如,假设您要清除所有TextBox,您可以执行类似这样的操作

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

对于ComboBox,你可以做同样的事情

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

答案 2 :(得分: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();
    }
} 
相关问题