Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

C# Referencing numbered Objects

  • 28-06-2010 02:45PM
    #1
    Registered Users, Registered Users 2 Posts: 1,842 ✭✭✭


    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, Registered Users 2 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