如何在C#的面板控件中清除控件,即TextBoxes,ComboBoxes,CheckBoxes等

时间:2019-01-26 08:39:23

标签: checkbox combobox textbox panel

我有一个在面板内部带有TextBoxes,ComboBoxes,CheckBoxes和DataGridView的表单。在“按钮单击”事件上,我可以按照以下步骤清除控件:

enter code here

按钮点击通话:

def prints():
    with open ("{}.txt".format(name), "r") as printer :
    contain = printer.readlines()
    print(''.join(contain))

name = input("Enter the file name : ")
try:
    prints()
    sys.exit()
except:
    pass

<more code>

但是: 我的面板“ MainPanel”中的控件未清除。我缺少什么?

1 个答案:

答案 0 :(得分:0)

此代码可解决问题:

public void ClearControlValues(Control Container)
    {

        foreach (Control c in Container.Controls)
        {
            if (c is CheckBox)
            {
                CheckBox cb = (CheckBox)c;
                cb.Checked = false;
            }

            if (c is TextBox)
            {
                TextBox tb = (TextBox)c;
                tb.Text = "";
            }

            if (c is ComboBox)
            {
                ComboBox cb = (ComboBox)c;
                cb.SelectedIndex = -1;
            }

            if (c is DateTimePicker)
            {
                DateTimePicker dtp = (DateTimePicker)c;
                dtp.Text = DateTime.Today.ToString();
            }

            if (c is DataGridView)
            {
                DataGridView dgv = (DataGridView)c;
                dgv.Rows.Clear();
                dgv.Refresh();

            }
        }


    }

通话:

ClearControlValues(MainPanel);

谢谢