travisowens Posted April 28, 2004 Posted April 28, 2004 Currently I'm using this code to clear all the TextBox.Text values in a GroupBox. (It may be not be pretty but it works). private void btnCallerClear_Click(object sender, System.EventArgs e) { foreach(Control myControl in grpLocation.Controls) { // TextBox test = myControl as TextBox; if ( myControl as TextBox == null ) { } else { ((TextBox)myControl).Text = ""; } } } I'm trying to make the code more programatic instead of hard typing the GroupBox's name and the best that I can come up with but DOES NOT work is... private void btnCallerClear_Click(object sender, System.EventArgs e) { foreach(Control myControl in (GroupBox)sender.Parent.Controls) { // TextBox test = myControl as TextBox; if ( myControl as TextBox == null ) { } else { ((TextBox)myControl).Text = ""; } } } How can I fix this, and does anybody have something a little bit more elegant? Quote Experience is something you don't get until just after the moment you needed it
Arch4ngel Posted April 28, 2004 Posted April 28, 2004 try : if( myControl is TextBox ) { ((TextBox)myControl).Clear(); // Same as .Text = "" } Quote "If someone say : "Die mortal !"... don't stay to see if he isn't." - Unknown "Learning to program is like going out with a new girl friend. There's always something that wasn't mentioned in the documentation..." - Me "A drunk girl is like an animal... it scream at everything like a cat and roll in the grass like a dog." - Me after seeing my girlfriend drunk and some of her drunk friend. C# TO VB TRANSLATOR
travisowens Posted April 28, 2004 Author Posted April 28, 2004 Bizarrely I get a runtime (not buld) error on myControl is TextBox and ((TextBox)myControl).Clear(); but I'm not concerned why. I was actually trying to do myControl is TextBox initially but it was this runtime error that made me finder this other way listed in my original post. Quote Experience is something you don't get until just after the moment you needed it
pendragon Posted April 28, 2004 Posted April 28, 2004 I have a class that I use for locking controls, clearing fields etc. I do something like this. for (int index = 0; index < this.Controls.Count; iIndx++) { switch (formName.Controls[iIndx].GetType().ToString()) { case "System.Windows.Forms.GroupBox": GroupBox groupBox; groupBox = (GroupBox)this.Controls[index]; for (int index1 = 0; index1 < groupBox.Controls.Count; index1++) { switch (groupBox.Controls[index1].GetType().ToString()) { case "System.Windows.Forms.TextBox": TextBox theControl; theControl = (TextBox)groupBox.Controls[index1]; theControl.Clear(); break; } } break; } } But this can get complicated depending on what you what to look for (ie groupbox's in groupbox's) Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.