|
-
Apr 20th, 2004, 10:15 PM
#1
Thread Starter
PowerPoster
C# - Clear a container of controls quickly.
I am almost ashamed to post such trivial code, but here is a little function that clears control values that are in a container control that you pass into it (like a groupbox or panel).
Code:
public void ClearControlValues(System.Windows.Forms.Control Container)
{
try
{
foreach(Control ctrl in Container.Controls)
{
if(ctrl.GetType() == typeof(TextBox))
((TextBox)ctrl).Text = "";
if(ctrl.GetType() == typeof(ComboBox))
((ComboBox)ctrl).SelectedIndex = -1;
if(ctrl.GetType() == typeof(CheckBox))
((CheckBox)ctrl).Checked = false;
if(ctrl.GetType() == typeof(Label))
((Label)ctrl).Text = "";
if(ctrl.GetType() == typeof(DateTimePicker))
((DateTimePicker)ctrl).Text = "";
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
You can add your own additions in there for other types of controls, I just translated this for someone else, and I didn't want to lose it because I know I may use this in the future.
So you would call it by passing in a groupbox or a panel that contains controls you want to clear the values of. If the container control contains controls that are not checked in this function, they are ignored.
-
Jul 30th, 2004, 06:06 PM
#2
There is slight problem with the above code, as it does not clear any conrols embeded within other container.
So adding extra two line and making it Recursive would fix it.
e.g
Code:
public void ClearControlValues(System.Windows.Forms.Control Container)
{
try
{
foreach(Control ctrl in Container.Controls)
{
if(ctrl.GetType() == typeof(TextBox))
((TextBox)ctrl).Text = "";
if(ctrl.GetType() == typeof(ComboBox))
((ComboBox)ctrl).SelectedIndex = -1;
if(ctrl.GetType() == typeof(CheckBox))
((CheckBox)ctrl).Checked = false;
if(ctrl.GetType() == typeof(Label))
((Label)ctrl).Text = "";
if(ctrl.GetType() == typeof(DateTimePicker))
((DateTimePicker)ctrl).Text = "";
if(ctrl.Controls.Count>0)
ClearControlValues(ctrl);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Just thougt some one else might find it useful, i use it quite a lot to clear my Form values.
[VBF RSS Feed]
There is a great war coming. Are you sure you are on the right side? Atleast I have chosen a side.
If I have been helpful, Please Rate my Post. Thanks.
This post was powered by : 
-
Oct 1st, 2004, 11:50 PM
#3
Thread Starter
PowerPoster
Your right, thanks for adding that. I normally don't have control containers within control containers, so I totally left that piece out.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|