简体   繁体   中英

How to retrieve multiple images from SQL Server database in picturebox in C# windows application?

I'm trying below code in c# windows application that's working fine to retrieve a single image from a SQL Server database table.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;

namespace ManagementSystem
{
    public partial class frmSearchResult : Form
    {
        public frmSearchResult()
        {
            InitializeComponent();
        }

        SqlConnection con;
        SqlCommand cmd;

        private void cmdSearch_Click(object sender, EventArgs e)
        {
            con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=managementsystem;Integrated Security=True");
            con.Open();

            cmd = new SqlCommand("Select M_Photo, S_Photo From Members where M_Number=15", con);

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();

            da.Fill(ds);

            if (ds.Tables[0].Rows.Count > 0)
            {
                MemoryStream ms = new MemoryStream((byte[])ds.Tables[0].Rows[0]["M_Photo"]);
                pic_M.Image = new Bitmap(ms);
            }
        }
    }
}

but I need to retrieve multiple images from database. When I append below code at the end, I get an error:

Parameter is not valid.

Appended code is

MemoryStream ms1 = new MemoryStream((byte[])ds.Tables[0].Rows[0]["S_Photo"]);
pic_S.Image = new Bitmap(ms1);

What is wrong with this? Please help.

Thanks!

The main problem was with the saving images in the right way. Use below code for each image to save images in the database image fields and use above questioned code to retrieve images.

//Convert image to binary
string imgpathC2 = txtH_C2.Text;
FileStream fsC2;
fsC2 = new FileStream(@imgpathC2, FileMode.Open, FileAccess.Read);
byte[] picbyteC2 = new byte[fsC2.Length];
fsC2.Read(picbyteC2, 0, System.Convert.ToInt32(fsC2.Length));
fsC2.Close();

//Add binary value to SQL parameter
SqlParameter picparaC2 = new SqlParameter();
picparaC2.SqlDbType = SqlDbType.Image;
picparaC2.ParameterName = "picC2";
picparaC2.Value = picbyteC2;

//use parameter in command
cmd.Parameters.Add(picparaC2);

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM