简体   繁体   English

从数据库到DataGrind的C#WPF图像

[英]C# WPF image from database to DataGrind

So, I've a class thats imports data from database to my application: 因此,我有一个将数据从数据库导入到我的应用程序的类:

class refresh : MainWindow
{
    public refresh(string tableName)
    {
        connection MyConnection = new connection();
        string sqlCommand = "SELECT * FROM " + tableName + "";
        DataTable dt_Silo = new DataTable();
        MySqlDataAdapter com_Silo = new MySqlDataAdapter(sqlCommand, MyConnection.con);
        com_Silo.Fill(dt_Silo);
        dataGrid.ItemsSource = dt_Silo.DefaultView;
    }      
}

I add data and the image by this: 我以此添加数据和图像:

 private void buttonProductAdd_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            byte[] imageBt = null;

            string uriPath = imageProduct.Source.ToString();
            string localPath = new Uri(uriPath).LocalPath;

            FileStream fstream = new FileStream(localPath, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fstream);
            imageBt = br.ReadBytes((int)fstream.Length);


            MySqlCommand com_ProductAdd = MyConnection.con.CreateCommand();
            com_ProductAdd.CommandText = "INSERT INTO product (NAME, AMOUNT, PICTURE) VALUES('" + textBoxProductAddName.Text + "', '" + textBoxProductAddAmount.Text + "', @IMG)";
            MyConnection.con.Open();
            com_ProductAdd.Parameters.Add(new MySqlParameter("@IMG", imageBt));
            com_ProductAdd.ExecuteNonQuery();
            MyConnection.con.Close();
            MessageBox.Show("Dodano produkt!");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

And at last I load the data to my dataGrind: 最后,我将数据加载到我的dataGrind中:

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        refresh RefreshProdukty = new refresh("product");
        dataGrid.ItemsSource = RefreshProdukty.dataGrid.ItemsSource;
    }

How do I display the image instead of "[]Byte Array" ? 如何显示图像而不是“ [] Byte Array”?

You can get the BitmapImage by using: 您可以使用以下方法获取BitmapImage

    private BitmapImage BytesToBitmapImage(byte[] bitmapBytes)
    {
        using (var ms = new MemoryStream(bitmapBytes))
        {
            var bitmapimage = new BitmapImage();
            bitmapimage.BeginInit();
            bitmapimage.StreamSource = ms;
            bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapimage.EndInit();

            return bitmapimage;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM