用户控制代码:
private string lastName;
public string LastName
{
get { return lastName; }
set
{
lastName = value;
textBox1.Text = value;
}
}
表格代码:
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand SqlCommand = new SqlCommand("Select LastName, Image from Employee", myDatabaseConnection))
{
int i = 0;
SqlDataReader DR1 = SqlCommand.ExecuteReader();
while (DR1.Read())
{
i++;
UserControl2 usercontrol = new UserControl2();
usercontrol.Tag = i;
usercontrol.LastName = (string)DR1["LastName"];
flowLayoutPanel1.Controls.Add(usercontrol);
}
}
}
使用上面的代码,我可以在每个用户控件的文本框中显示数据库中的每个 LastName。如何将数据库中的图片显示到每个用户控件的图片框?
这是我从数据库中显示单个图像的方式:
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand SqlCommand = new SqlCommand("Select LastName, Image from Employee where ID = @a", myDatabaseConnection))
{
SqlCommand.Parameters.AddWithValue("@a", textBox1.Text);
DataSet DS = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(SqlCommand);
da.Fill(DS, "Images");
var imagesTable = DS.Tables["Images"];
var imagesRows = imagesTable.Rows;
var count = imagesRows.Count;
if (count <= 0)
return;
var imageColumnValue =
imagesRows[count - 1]["Image"];
if (imageColumnValue == DBNull.Value)
return;
var data = (Byte[])imageColumnValue;
using (var stream = new MemoryStream(data))
{
pictureBox1.Image = Image.FromStream(stream);
}
}
}