0

I am a beginner with coding and trying to solve simple problem:

I have list with three columns and trying to access values stored in the list. And it gives me no answer... any idea? thanks

private void btnImage1Load_Click(object sender, EventArgs e)
    {
        openFileDialog1.ShowDialog();
        pictureBox1.ImageLocation = openFileDialog1.FileName;                    
    }

    public class ListThreeColumns
    {
        public int XCoord { get; set; }
        public int YCoord { get; set; }
        public Color Color { get; set; }
    }

    private List<ListThreeColumns> GetPixels()
    {
        Bitmap picture = new Bitmap(pictureBox1.Image);

        List<ListThreeColumns> colorList = new List<ListThreeColumns>
        {

        };

        for (int y = 0; y < picture.Height; y++)
        {
            for (int x = 0; x < picture.Width; x++)
            {
                colorList.Add(new ListThreeColumns { XCoord = x, YCoord = y, Color = picture.GetPixel(x, y) });
            }
        }
        return colorList;
    }


    private void btnScanPixels_Click(object sender, EventArgs e)
    {
        List<ListThreeColumns> seznamBarev = GetPixels();
       MessageBox.Show(seznamBarev[6].ToString());


    }
  • 1
    Possible duplicate of [Why does a collection initializer expression require IEnumerable to be implemented?](http://stackoverflow.com/q/3716626/299327) – Ryan Gates Nov 19 '12 at 23:07

2 Answers2

4

In this line:

MessageBox.Show(seznamBarev[6].ToString());

... you're accessing element 6 of the list, but then just calling ToString on it. As you haven't overridden ListThreeElements (which would be better named Pixel, by the way) that means the result won't be particularly useful.

You could write:

ListThreeColumns pixel = seznamBarev[6];
MessageBox.Show(string.Format("{0}, {1} - {2}", pixel.X, pixel.Y, pixel.Color);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

What do you want to do? If you want to show each item in string you can use Jon way. But it's better to move operations to your class. If you override 'ToString()' method in ListThreeColumns class, your code works correctly, without change.

 public class ListThreeColumns
{
    public int XCoord { get; set; }
    public int YCoord { get; set; }
    public Color Color { get; set; }

    public override ToString()
    {
         return string.Format("X={0}, Y={1}, Color=({2};{3};{4})", 
             this.XCoord , this.YCoord , Color.R,Color.G,Color.B );
    }
}
Behnam
  • 15
  • 1
  • 7