Click here to Skip to main content
15,943,148 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
I am creating a list variable with my Structure to add dynamically values.
List<emp> empList = new List<emp>();
 emp em = new emp { 
                ecode=textBox1.Text,
                ename=textBox2.Text
            };
            empList.Add(em);


After adding the values I want to change the value whose index is 3(or it's depends on user).
so I am trying this:

empList[listBox1.SelectedIndices[0]].ename = textBox3.Text;


but this line gives error:
Cannot modify the return value of 'System.Collections.Generic.List<NewTech.emp>.this[int]' because it is not a variable


I am searched on google but cannot find the proper result on this..

So my question is :
how to change the List object value with index in C#?

Thanks in advanced..

Regards
Jayanta.
Posted

1 solution

Hi - Simple answer:

Don't use a struct when not appropiate - use a reference type - so your emp struct should be a class if you want to change the values like this.
Rule of Thumb: Never use structs (or read the longer explaination with the same conclusion http://msdn.microsoft.com/en-us/library/ms173109.aspx[^]

OT: Btw emp is not a very good type name - type names should be written uppercase, no abbreviations etc. - I think it's a good idea to go for "common" standards, though personal ones are better than nothing... http://msdn.microsoft.com/en-us/library/ms229042.aspx[^]

Kind regards,

Johannes
 
Share this answer
 
Comments
JayantaChatterjee 12-Aug-14 10:09am    
Thank you it's worked..
but I am using Struc instead of class because of performance(the collection can be upto 50 or more items).
is there any other way to do this???
johannesnestler 12-Aug-14 10:27am    
50? don't even think about a struct - it holds strings so size will be more than 16 bytes for shure... (so no performance benefit) Other way? - of course you can assign a new struct each time you want to change the list "entry" - but you don't want to do that. So in your case change it to a class - it was wrong to define a struct in the first place (http://msdn.microsoft.com/en-us/library/ms229017.aspx)
JayantaChatterjee 12-Aug-14 10:32am    
Thank you Sir, I appreciate Your suggestion..

Its help me lots.. :-)
johannesnestler 12-Aug-14 10:46am    
you are welcome - good luck with your Projects!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900