If user enters 5 this loop creates 5 pictureboxes
int.TryParse(text10.Text, out int a); for (i = 0; i < a; ++i) { PictureBox pb = new PictureBox(); pb.Name = ("pic" + (i + 1)).ToString(); pb.Location = new Point(100, 150 + (850 * i));////this (850 * i) Size picsize = new Size(800, 800); pb.Size = picsize; pb.BorderStyle = BorderStyle.FixedSingle; pb.SizeMode = PictureBoxSizeMode.StretchImage; pb.Click += clickonimage; pb.Cursor = Cursors.Hand; this.Controls.Add(pb); }
Here I have a click event for selecting image of each picture box
My question is…
How can I insert those images of pictureBoxes into SQL SERVER at once?
can anyone help ?
appreciate it.
Advertisement
Answer
If you have 5 picture boxes in your application and in your database table there are 5 columns to store image data then do as following demo code does
var pictureBoxNames = Enumerable .Range(1, 5) .Select(i => "pic" + i); PictureBox[] pictureBoxes = Controls .OfType<PictureBox>() .Where(p => pictureBoxNames.Contains(p.Name)) .ToArray(); var builder = new SqlConnectionStringBuilder() { DataSource = "MyServerAddress", //your server name InitialCatalog = "DataTable1" //your data table name }; using (var sqlConnection = new SqlConnection(builder.ConnectionString)) { sqlConnection.Open(); var columns = string.Join(", ", pictureBoxNames.Select(s => $"[{s}]")); var pars = string.Join(", ", pictureBoxNames.Select(s => $"@{s}")); //Replace 'Table1' with your data table name here string commandText = $"INSERT INTO [Table1] ({columns}) VALUES ({pars})"; using (var insertCommand = new SqlCommand(commandText, sqlConnection)) { var imageConverter = new ImageConverter(); Func<Image, object> ToByteArray = img => imageConverter.ConvertTo(img, typeof(byte[])); var ps = pictureBoxes .Select(p => new SqlParameter($"@{p.Name}", ToByteArray(p.Image))) .ToArray(); insertCommand.Parameters.AddRange(ps); insertCommand.ExecuteNonQuery(); } }