Click here to Skip to main content
15,912,578 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a list 'objlistCropped' and when i tried to add values to this list using a foreach loop all the list value is replaced by last value.
C#
string strCroppedImagePaths = @"C:\CropImages";
            Selected objCropped = new Selected();
            Source objSource = new Source();
            ArrayList listCropped = new ArrayList();
            DirectoryInfo d = new DirectoryInfo(strCroppedImagePaths);

         FileInfo[] file = d.GetFiles("*.Jpeg").OrderBy(fi => int.Parse(Path.GetFileNameWithoutExtension(fi.Name).TrimStart("Image".ToArray()))).ToArray();
            DataTable dt = new DataTable();
            int RowID = 0;

            foreach (FileInfo file2 in file)
            {
                if (file2.Extension == ".jpg" || file2.Extension == ".Jpeg" || file2.Extension == ".gif" || file2.Extension == ".png" || file2.Extension == ".bmp")
                {
                    //listCropped.Add(file2);
                    string strCroppedImagename = file2.Name;
                   
                    RowID++;
                    
                    objCropped.Image = strCroppedImagename;
                    objlistCropped.Add(objCropped);
                }
            }


if folder having 10 images, all the list values are last image (Image10).
Posted
Updated 20-Jan-15 3:50am
v5

You wanted to write this one surely (just a typing error):

C#
//listCropped.Add(file2);
 foreach (FileInfo file2 in file)
 {
      if (file2.Extension == ".jpg" || file2.Extension == ".Jpeg" || file2.Extension == ".gif" || file2.Extension == ".png" || file2.Extension == ".bmp")
            //string strCroppedImagename = file2.Name;
            string strCroppedImagename = file.Name;
 
Share this answer
 
v2
Your code does not show where 'objlistCropped is defined, but, assuming it is a List of Type 'Selected:

1. The error occurs because you are re-using the same instance of a Selected, 'objCropped, each time: 'objCropped is clearly a reference Type.

2. You can fix this, I am pretty sure, by just creating a new Instance of 'Selected to add each time you update the List:
C#
objCropped = new Selected();
objCropped.Image = strCroppedImagename;
objlistCropped.Add(objCropped);
Of course, if you used this approach, then you could declare 'objcropped at the start of your code without initializing it.
 
Share this answer
 

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