问题
I wanna clean my groupbox items after i click an button.
I tried some code blocks, but they don´t work for reset controls.
I don´t wanna remove or delete it, I just wanna reset the items in the groupbox.
This is working for remove groupbox items.
public void ClearPanels(GroupBox control)
{
control.Controls.Clear();
}
or this
groupBox2.Controls.Clear();
It looks like this, before click.
And when I click the button, as you can see on the right side.
It is removed, but I want to reset it.
Any ideas how I can do this ?
回答1:
I'm going to asume that clear means to leave it all by default. You need to llop all the controls inside the groupbox and depending on what control they are do something or something else.
foreach (Control ctr in GB.Controls)
{
if (ctr is TextBox)
{
ctr.Text = "";
}
else if (ctr is CheckedListBox)
{
CheckedListBox clb = (CheckedListBox)ctr;
foreach (int checkedItemIndex in clb.CheckedIndices)
{
clb.SetItemChecked(checkedItemIndex, false);
}
}
else if (ctr is CheckBox)
{
((CheckBox)ctr).Checked = false;
}
else if (ctr is ComboBox)
{
((ComboBox)ctr).SelectedIndex = 0;
}
}
I dont know what Deneyim and Not are, but i guess you get the idea of checking what it is and asigning the value you want
回答2:
I think the term clear
depends a little on the kind of controls you use. While for a TextBox
you probably want to empty the Text
property, for a ListBox
you probably want to remove all items. So there is no common Clear()
method for controls.
What you can do is something like that:
public void ClearPanels(GroupBox control)
{
foreach(Control childControl in control.Controls)
childControl.ResetText();
}
This iterates through all child Control
s in your GroupBox
and resets the Text
property of them. You may wish to add special treatment for certain types of Control
.
If your GroupBox
contains nested controls (such as another GroupBox
with further controls on it), you may need to make this method recursive:
public void ClearPanels(Control control)
{
foreach(Control childControl in control.Controls)
{
childControl.ResetText();
ClearPanels(childControl); // recursive call
}
}
To really "clear" your controls, you have to check their specific type. So a little advanced method could be this:
public void ClearPanels(GroupBox control)
{
foreach(ListBox listBox in control.Controls.OfType<ListBox>())
{
listBox.Items.Clear();
// do more ListBox cleanup
}
foreach(CheckedListBox listBox in control.Controls.OfType<CheckedListBox>())
{
listBox.Items.Clear();
// do more CheckedListBox cleanup
}
foreach(ListView listView in control.Controls.OfType<ListView>())
{
listView.Items.Clear();
// do more ListView cleanup
}
foreach(CheckBox checkBox in control.Controls.OfType<CheckBox>())
{
checkBox.Checked = false;
// do more CheckBox cleanup
}
// etc...
}
来源:https://stackoverflow.com/questions/38069870/how-to-reset-groupbox-items