CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: List item name

  1. #1
    Join Date
    Oct 2010
    Posts
    3

    List item name

    Hi,

    I have a list which is named:

    List<TestList> TestList = new List<TestList>();

    I am able to the value from it by using e.g.
    string value = TestList[0].ListItem1

    Is it possible to make ListItem1 variable?
    so something like:

    string variable = "ListItem1"
    string value = TestList[0].(string)variable

    Thanks

  2. #2
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: List item name

    In answer - yes, you can do this with reflection.

    However you shouldn't - it leads to runtime errors rather than compile-time errors (so they tend to happen infront of users which makes you look like an idiot) as well as being inefficient.

    I'd suggest having a switch statement e.g.

    Code:
    string variable = "ListItem1"
    string value = null;
    
    switch (variable)
    {
        case "ListItem1":
            value = TestList[0].ListItem1;
            break;
    
        case "ListItem2":
            value = TestList[0].ListItem2;
            break;
    
        // etc
    }
    However code like this in my experience is caused by a fault in the overall code design - what is it you're trying to do exactly ? ListItem1/ListItem2 suggests to me that you're trying to hook up a UI in some way. In which case a Dictionary might be a better option.

    Darwen.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

  3. #3
    Join Date
    Oct 2010
    Posts
    3

    Re: List item name

    Thanks for your quick reply,
    I understand I have probably chosen the wrong setup.

    I want to compare a ListItem to a value.

    So something like:

    Code:
    if (TestList[0].(string)variable == "A")
    {
    }
    where (string)variable is "ListItem1" and is chosen from a combobox.
    Could also be "ListItem2"
    etc.
    Last edited by scarm; October 6th, 2011 at 10:16 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured