Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert type 'System.Windows.Forms.Control' to 'T'

Tags:

c#

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!");
}
like image 657
Theofanis Pantelides Avatar asked Dec 17 '22 23:12

Theofanis Pantelides


1 Answers

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!");
}
like image 62
Itay Karo Avatar answered Dec 30 '22 16:12

Itay Karo