c# Show image database for each usercontrol

2019-09-02 19:48发布

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

Form

    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?

1条回答
Evening l夕情丶
2楼-- · 2019-09-02 20:36

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;
    }
查看更多
登录 后发表回答