0

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.

11
  • 1
    I read this as creation of dynamic objects - please edit to clarify either way. Commented Jan 5, 2010 at 22:03
  • 3
    What do you mean by create an object? Do you mean instantiation or do you mean creating a class at runtime? Commented Jan 5, 2010 at 22:04
  • 4
    I guess I fail at asking questions. >.> Commented Jan 5, 2010 at 22:13
  • 1
    @serhio We can't assume Hazior doesn't understand how to use the new operator by the question. The intention of his question is to discover new (no pun) and possibly various ways to dynamically create objects. It doesn't reflect on his fundamental knowledge. Indeed there are different ways to create objects. Commented Jan 5, 2010 at 22:27
  • 1
    @Harizor: so what is your question, I don't understand. You know about Label myLabel = new Label(); more that than, you can add it to the parent by using lebelParent.Controls.Add(myLabel); So, what is still unclear? Commented Jan 5, 2010 at 22:39

5 Answers 5

9

I use the new keyword to dynamically create objects.

Sign up to request clarification or add additional context in comments.

6 Comments

thanks for this. i didn't think about this exotic usage of the new keyword ;)
The answer worth the (initial) question.
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: 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: Then I apologize I misinterpreted.
|
2

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.)

2 Comments

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: If this answer dawned on you, make it as answer and let's close the topic.
2

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.

Comments

2

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.)

Comments

1

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.

3 Comments

David, go down. The new keyword is in discussion here :)
David is right here. Creating objects dynamically is a different thing. AFAIK VB has a late binding which C# does not have.
@jdk - whoops, thanks - and thanks for saving my blushes Logan.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.