1

I'm trying to load my pictures into dynamically created pictureboxes. The pictures will be retrieved from a mysql server which is located on my local network. I've been able to get one picture in a picturebox by changing the query to pick only 1 id. so I know it works with one at the time.

Code:

private void ass_wijzig_Load(object sender, EventArgs e)
    {

        string query = "Select Image From Product";
        MySqlCommand cmd = new MySqlCommand(query,connection);
       // MySqlDataReader reader = cmd.ExecuteReader();
        var da = new MySqlDataAdapter(cmd);
        var ds = new DataSet();
        da.Fill(ds, "Image");
        int count = ds.Tables["Image"].Rows.Count;
        DataRow myrow;
        byte[] mydata = new byte[0];
        int x = 10;
        int y = 10;
        for (int i = 0; i < 2; i++)
        {
             myrow= ds.Tables["Image"].Rows[i];
            // var data = (Byte[])(ds.Tables["Image"].Rows[i]["Image"]);
             mydata = (Byte[])(ds.Tables["Image"].Rows[i]["Image"]);
             Stream[] str = new MemoryStream[i];
             str[i] = new MemoryStream(mydata);
             PictureBox[] pbx = new PictureBox[i];
             pbx[i] = new PictureBox();
             pbx[i].Size = new Size(150, 150);
             pbx[i].SizeMode = PictureBoxSizeMode.StretchImage;
             pbx[i].Image = Image.FromStream(str[i]);
             pbx[i].Visible = true;
             pbx[i].Location = new Point(x, y);
             x += pbx[i].Location.X + pbx[i].Width;
             this.Controls.Add(pbx[i]);
        }

The exception is thrown at Stream[] str = new MemoryStream[i]; I would be honored if somebody knew the problem,

Thanks in advance

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
  • you shouldn't assume the upper bound of `i`. – Daniel A. White Jun 01 '14 at 16:12
  • 1
    This piece of code is so riddled with weird statements, you should probably take it apart into different blocks: read byte[]s from database, transform byte[] to stream, create image from stream, create picturebox from image. As it is, it's a mess of superfluous code. Drop the dataadapter/datatable and use a simple datareader. Drop all arrays. You don't need them. Loop over your datareader and create one picturebox each loop. – nvoigt Jun 01 '14 at 16:14

1 Answers1

0

The problem is that arrays are 0-indexed.

Stream[] str = new MemoryStream[i];

Creates an array of length i, so the valid indices are 0 ... i - 1.

Then you do:

str[i] = new MemoryStream(mydata);

Which tries to access index i, which is invalid.

Looking at your code, I'm not sure why you're using an array here at all instead of a normal variable. Just do:

Stream str = new MemoryStream(myData); 

instead.

ChaseMedallion
  • 20,860
  • 17
  • 88
  • 152