Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

C# Referencing numbered Objects

Options
  • 28-06-2010 3:45pm
    #1
    Registered Users Posts: 1,830 ✭✭✭


    Hi all,

    I've got 10 Textboxs which I need to populate.
    I'm looking for a more efficient way of doing this than using 10 statements such as;

    txtMsgLine1.Text = Object.MessageLine1;
    txtMsgLine2.Text = Object.MessageLine2; ...... etc.

    Is this possible, maybe via a loop?

    BTW I can change the textboxs, i.e I could put them in an array but I can't change the object properties - e.g MessageLine1.


Comments

  • Registered Users Posts: 515 ✭✭✭NeverSayDie


    Well, if your TextBoxes have a common naming scheme like that, and assuming this is ASP.NET, you could use FindControl() calls to access them dynamically instead of directly.

    If you can't change/extend the implementation of your object that stores the text though (exposing the message lines as a List<> of strings or some such) then you're pretty much out of luck. You probably could enumerate its properties at runtime using something from the Reflection/Type namespaces - GetType() and GetProperty() spring to mind - but tbh that may make for less readable and less performant code than you've already got.

    Another option might involve using extension methods (assuming the newer versions of C#, Framework 3.0 onwards I think) to add an interface that will iterate through the properties and expose them in a collection of some sort. Don't know too much about them, but AFAIK you can do that sort of thing. Again, may not be a good idea in terms of readable code.


Advertisement