
Question:
I am trying to make a Generic FindControl method and I get the following error:
Cannot convert type 'System.Windows.Forms.Control' to 'T'
Code:
public T Control<T>(String id) { foreach (Control ctrl in MainForm.Controls.Find(id, true)) { return (T)ctrl; // Form Controls have unique names, so no more iterations needed } throw new Exception("Control not found!"); }
Solution:1
try this
public T Control<T>(String id) where T : Control { foreach (Control ctrl in MainForm.Controls.Find(id, true)) { return (T)ctrl; // Form Controls have unique names, so no more iterations needed } throw new Exception("Control not found!"); }
Solution:2
You could always bend the rules and do a double cast. Eg:
public T Control<T>(String id) { foreach (Control ctrl in MainForm.Controls.Find(id, true)) { return (T)(object)ctrl; } throw new Exception("Control not found!"); }
Solution:3
As T is unconstrained, you could pass anything for the type parameter. You should add a 'where' constraint to your method signature:
public T Control<T>(string id) where T : Control { ... }
Solution:4
How are you calling this method, have you got an example?
Also, I'd add a constraint to your method:
public T Control<T>(string id) where T : System.Windows.Forms.Control { // }
Solution:5
While other people have already correctly pointed out what the problem is, I just want to chime in that this would be quite suitable for an extension method. Don't upvote this, this is actually a comment, I'm just posting it as an answer so that I can gain the ability to write longer and format my code better ;)
public static class Extensions { public static T FindControl<T>(this Control parent, string id) where T : Control { return item.FindControl(id) as T; } }
So that you can invoke it like so:
Label myLabel = MainForm.Controls.FindControl<Label>("myLabelID");
Solution:6
Change your method signature to this:
public T Control<T>(String id) where T : Control
Stating that all T's are in fact of type Control
. This will constrain T and the compiler knows you can return it as T.
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon