I'm having a memory exception because I only read my table's image column without specifying that it's a byte. How can I do this?

con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();

            if (rdr.HasRows)
            {
                while (rdr.Read())
                {
                    FileStream fs = new FileStream("image.bmp", FileMode.Create);

                    byte[] picbyte = (byte[])rdr["userimage"];
                    fs.Write(picbyte, 0, picbyte.Length);

                    displaypb.Image = Image.FromFile("image.bmp");

                    fs.Close();
                    fs = null;
}
}

This is where I think i'm having problems. First of all it cannot be converted to a string. I need to set it to bytes, at least that's what I think. Maybe .getbytes, but how?

byte[] picbyte = (byte[])rdr["userimage"];

Check this code I did a couple of weeks ago. The pictues are retreived from DB and shown in listbox:

List<ImageList> list;
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonLoad_Click(object sender, EventArgs e)
        {
            this.listBox1.Items.Clear();
            list = new List<ImageList>();
            using (SqlConnection sqlConn = new SqlConnection(connString))
            {
                string query = String.Format(@"SELECT PictureName, MyImage FROM Images");
                SqlCommand cmd = new SqlCommand(query, sqlConn);
                cmd.Connection.Open();
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        ImageList _image = new ImageList();
                        _image.imageName = (string)reader[0];
                        byte[] data = (byte[])reader[1]; //be careful here number 1 is 2nd column in DB (1st is picName, 2nd is Image)
                        using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
                        {
                            Image image = new Bitmap(ms);
                            _image.imagePicture = image;
                            list.Add(_image);
                        }
                    }
                }
            }
            if (list.Count == 0)
                MessageBox.Show("There are no pictures in the database.");
            else
                ShowImagesAndList();
        }

        private void ShowImagesAndList()
        {
            foreach (ImageList image in list)
                this.listBox1.Items.Add(image.imageName);
        }

I think I need to work on this line

byte[] picbyte = (byte[])rdr["userimage"];)

I need to set it to .getbytes.. But the arguments is quite complicated for me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.