-
October 6th, 2011, 08:06 AM
#1
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
-
October 6th, 2011, 09:14 AM
#2
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.
-
October 6th, 2011, 10:13 AM
#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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|