JayT
JayT

Reputation: 107

Dynamically cast a control type in runtime

I have an application whereby I dynamically create controls on a form from a database. This works well, but my problem is the following:

    private Type activeControlType;        

    private void addControl(ContainerControl inputControl, string ControlName, string Namespace,
        string ControlDisplayText, DataRow drow, string cntrlName)
    {
        Assembly assem;
        Type myType = Type.GetType(ControlName + ", " + Namespace);
        assem = Assembly.GetAssembly(myType);

        Type controlType = assem.GetType(ControlName);
        object obj = Activator.CreateInstance(controlType);
        Control tb = (Control)obj;
        tb.Click += new EventHandler(Cntrl_Click);
        inputControl.Controls.Add(tb);
        activeControlType = controlType;
    }

    private void Cntrl_Click(object sender, EventArgs e)
    {
         string test = ((activeControlType)sender).Text;  //Problem ???
    }

How do I dynamically cast the sender object to a class that I can reference the property fields of it.

I have googled, and found myself trying everything I have come across..... Now I am extremely confused... and in need of some help

Thnx

JT

Upvotes: 2

Views: 12396

Answers (3)

Sergey Shuvalov
Sergey Shuvalov

Reputation: 2128

You need to use Visitor pattern. For example: http://www.dofactory.com/Patterns/PatternVisitor.aspx#_self1

Upvotes: 0

CodesInChaos
CodesInChaos

Reputation: 108790

You can only cast to a type known at compile-time. So either you need to use a known baseclass or interface you can cast to, or you need to use reflection. In C# 4 the reflection based approach is much easier than in earlier versions, since it introduces the dynamic keyword. I prefer the statically typed approach where possible.

In C# 4 you can use dynamic:

dynamic dynSender=(dynamic)sender;
dynSender.Text="A";

Or if you know it's derived from Control:

Control controlSender=(Control)sender;
controlSender.Text="A";

And since you already cast to Control in your creation code, you know that your object is derived from Control in your example. And since the Text property is declared in Control this is enough to access it.

Upvotes: 7

JohnD
JohnD

Reputation: 14757

In your event handler, you can check the type using "is":

if (sender is TextBox)
{
   var textBox = (TextBox)sender;
   textbox.Text = "hello";
}

Upvotes: 0

Related Questions