views:

491

answers:

5

What ways can you dynamically create controls in C#?

This was objects at first but it would have been more precise to say controls. My terminology was messed up. Thanks Joel.

Edit{ Controls that are created during runtime. And are able to be accessed and edited by the program. Does this help? }

I like the idea of Dynamic creation and was wondering what ways there were to do this.

Please only one per answer, I would like to see how people rank them.

eg

private Label _lblCLastName = new Label(); 
private static List<ChildrenPanel> _ListCP = new List<ChildrenPanel>(); 

public void CreatePanel(Panel Container) 
{ 
    // Created Controls
    #region Controls 
    _pnlStudent.Controls.Add(_lblCLastName); 
    //  
    // lblCLastName 
    //  
    _lblCLastName.AutoSize = true; 
    _lblCLastName.Location = new System.Drawing.Point(6, 32); 
    _lblCLastName.Name = "lblCLastName"; 
    _lblCLastName.Size = new System.Drawing.Size(58, 13); 
    _lblCLastName.TabIndex = 10; 
    _lblCLastName.Text = "Last Name"; 

    // Adds controls to selected forms panel 
    Container.Controls.Add(_pnlStudent); 
    // Creates a list of created panels inside the class 
    // So I can access user input 
    ListCP.Add(this); 

} 

This is a code snippet from something that is close to what I'm talking about. I made another post but didn't quite post the question right. I will be deleting it but atm it is still viewable.

If there are still problems please be constructive I don't mind negitive input as long as it's helpful.

Edit: I was able to get some answers I was looking for. Thank you to everyone who replied. I will close this when I am able too. If someone else can close it that would be appreciated.

+9  A: 

I use the new keyword to dynamically create objects.

Hogan
thanks for this. i didn't think about this exotic usage of the new keyword ;)
Joachim Kerschbaumer
The answer worth the (initial) question.
serhio
It may be but it was created as a slight and not as an answer. Instead of helping assisting me in properly phrasing my question he mocked me and apparently that sort of thing gets support.
Hazior
@Hazior: because is not clear what exactly you wondering.
serhio
@serhio: Haha mocking me through bad english how funny.
Hazior
@Hazior: Actually no mock was intended. new does create objects dynamically. As someone who started programming in C where I had to `alloc()` space for pointers to stucts, I often feel people who have only used modern languages don't really have a feel for what is happening and the POWER of new.
Hogan
@Hogan: Then I apologize I misinterpreted.
Hazior
+1  A: 

Assuming you are talking about the creation of dynamic objects:

You'll obviously need a library to support this, unless you want to get into Reflection.Emit yourself - LinFu supported this in version 1:

http://code.google.com/p/linfu/

However, it's a feature that was dropped before version 2 I seem to remember.

David M
Is that first word a verb?
John K
David, go down. The `new` keyword is in discussion here :)
serhio
David is right here. Creating objects dynamically is a different thing. AFAIK VB has a `late binding` which C# does not have.
JCasso
@jdk - whoops, thanks - and thanks for saving my blushes Logan.
David M
+2  A: 

Anonymous Types, C# 3.x

This is fairly dynamic-esque because you don't have to code a class template to get custom objects.

// An anonymous object with two properties: obj.Name and obj.Age
var obj = new { Name = "Joe", Age = 35  };

The compiler will infer the Types of the properties from the initialization values you provide.

The type is not accessible from your source code, but can be seen in the IL. However if you create multiple anonymous objects with the same properties the C# compiler will use the same type for all of them.

// All objects use the same anonymous type
var obj1 = new { Name = "Joe", Age = 1  };
var obj2 = new { Name = "Art", Age = 30  };
var obj3 = new { Name = "Sally", Age = 25  };

// A different (second) anonymous type
var objDifferent = new { Phone = "555-555-1212", Name = "Joe", Age = 1  };

Stipulations There are more, but these are important.

  • var can only be used at the method scope (as a local variable), not the class scope.
  • anonymous objects have read-only properties; you cannot assign data back to them.
John K
+2  A: 

Activation (for remote objects too)

Use the System.Activator class' overloaded Activator.CreateInstance methods. This gets into the realm of creating objects locally or remotely.

using System;

/* Create instances of a Random number generator (or any class)
 *  without using the 'new' operator.
 */
Random rand1 = Activator.CreateInstance<Random>();
Random rand2 = (Random)Activator.CreateInstance(typeof(Random));
//etc...

(MSDN Documentation about Remote Objects.)

John K
+2  A: 

Creating GUI objects dynamically can be extremely useful, however, it can also be a nightmare for maintenance.

A good rule of thumb is to limit the amount of GUI object you dynamically create.

One situation where you may actually want to use a dynamically created GUI object is when you don't know the amount or count of objects you need. For example, one label for each row in a result set (even then you may consider a DataGrid or GridView type object).

This works for both WinForms and ASP.NET. Just be sure to document your code correctly.

My advice would be to stick with the Visual Designer for simpler forms and only create and add objects dynamically when it's absolutely necessary.

(FWIW, the code snippet you posted could probably be simplified and/or refactored as it seems to be going in the wrong direction.)

This is more what I am looking for. Perhaps I am asking it in the wrong way? So many people went in another direction.
Hazior
@Hazior: If this answer dawned on you, make it as answer and let's close the topic.
serhio