c#显示每个用户控件的图像数据库

本文关键字:控件 图像数据库 用户 显示 | 更新日期: 2023-09-27 18:13:36

Usercontrol1

    private string lastName;
private string nnovo;
public string LastName
//how use picturebox in usercontrol to retrieve image
{
get { return lastName; }
set
{
lastName = value;
label2.Text = value;
}
}
public string Nnovo {
get { return nnovo; }
set {
nnovo = value;
label1.Text = value;}
}

表单

    Button btn = (Button)sender;
SqlCommand cm = new SqlCommand("SELECT tblCategory.Categoryname, tblProduct.Productname,tblProduct.description FROM tblCategory INNER JOIN tblProduct ON tblCategory.Categoryid = tblProduct.Categoryid where tblCategory.Categoryname= '" + btn.Text + "'", cn);
try
{
SqlDataReader dr = cm.ExecuteReader();
flowLayoutPanel2.Controls.Clear();
flowLayoutPanel2.Update();
while (dr.Read())
{
UserControl1 user = new UserControl1();
user.Nnovo = (string)dr["Productname"].ToString();//Adds the values ​​of the database in label1 the usercontrol
user.LastName = (string)dr["description"].ToString(); //Adds the values ​​of the database in label2 the usercontrol
flowLayoutPanel2.Controls.Add(user);//Load usercontrol1 in flowlayoutpanel
flowLayoutPanel2.Update();
} dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}

通过上面的代码,我可以在每个用户控件的标签中显示数据库的每个"产品名称"answers"描述"。如何为每个picturebox用户控件显示数据库的图像?

c#显示每个用户控件的图像数据库

假设图像存储为字节数组,那么这个函数就可以了。只需将图像控件的源设置为返回的BitmapImage

    private BitmapImage byteToImage(byte[] array)
    {
        BitmapImage img = null;
        if (array != null && array.Length > 0)
        {
            using (MemoryStream stream = new MemoryStream(array))
            {
                stream.Position = 0;
                img.BeginInit();
                img.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                img.CacheOption = BitmapCacheOption.OnLoad;
                img.UriSource = null;
                img.StreamSource = stream;
                img.EndInit();
            }
            img.Freeze();
        }
        return img;
    }