c#为每个用户控件显示图像数据库 [英] c# Show image database for each usercontrol

查看:23
本文介绍了c#为每个用户控件显示图像数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户控件1

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

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

With the above code I can show each "product name" and "description" of the database in the label of each usercontrol. How to show the image of the database for each picturebox usercontrol?

推荐答案

假设图像存储为字节数组,这个函数应该可以解决问题.只需将图像控件的源设置为返回的 BitmapImage

Assuming the image is stored as byte array this function should do the trick. Simply set the Image Control's source to the returned 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;
    }

这篇关于c#为每个用户控件显示图像数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆