I have an object of type
Form, called
Form1. Then I have another object of type
MyClass (a class I created) called
Object1. I'm trying to write a
get() method within Form1 that will allows me to get the value of most any control within it.
I'm guessing there's a more elegant way to do this, but here's what I've got so far:
Code:
public string get(string control_name) {
foreach (Control ctrl in this.Controls) {
// If this is the right control
if (ctrl.Name == control_name) {
return returnValue(ctrl);
// Look inside container elements
} else if (ctrl.Controls.Count > 0) {
string tmp = getDeeper(ctrl, control_name);
// If tmp isn't "" then we found control_name and it wasn't "".
// Note that if we did find control_name but it's value was ""
// then we'd keep looking for it as if we haven't found it yet.
// This would cause the function to take longer but the final
// result is the same.
if (tmp != "") return tmp;
}
}
return "";
}
private string getDeeper(Control this_control, string control_name) {
foreach (Control ctrl in this_control.Controls) {
// If this is the right control
if (ctrl.Name == control_name) {
return returnValue(ctrl);
// Look inside container elements
} else if (ctrl.Controls.Count > 0) {
string tmp = getDeeper(ctrl, control_name);
// See the comment above in the get() method
if (tmp != "") return tmp;
}
}
return "";
}
private string returnValue(Control this_control) {
// If it's a textbox then just return the .Text()
if (this_control.ToString().StartsWith("System.Windows.Forms.TextBox")) {
return this_control.Text;
// Combo box
} else if (this_control.ToString().StartsWith("System.Windows.Forms.ComboBox")) {
return this_control.Text;
// Radio button
} else if (this_control.ToString().StartsWith("System.Windows.Forms.RadioButton")) {
return this_control.Checked.ToString();
} else {
return "";
}
}
So the error (shown in red above) is due to the fact that
this_control is being treated as a generic control, however the
if statement that leads me to that offending line guarantees that the control is indeed a radio button (and therefore should have a
Checked() method).
Is there a way for me to "typecast" this_control as a RadioButton so that the compiler is happy?
OR am I being obtuse and there's some magical way of making a generic
get() method using native C# tools?