如何插入由for循环创建的图片框的图像?



如果用户输入5,这个循环将创建5个图片框

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);
}

这里有一个click事件用于选择每个图片框的图像

我的问题是……

我如何插入那些图像的pictureBoxes到SQL SERVER一次?

有人能帮忙吗?

欣赏它。

如果你的应用程序中有5个图片框,在你的数据库表中有5列存储图像数据,那么按照下面的演示代码做

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();
}
}

最新更新