繁体   English   中英

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

[英]C# WPF image from database to DataGrind

因此,我有一个将数据从数据库导入到我的应用程序的类:

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

我以此添加数据和图像:

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

    }

最后,我将数据加载到我的dataGrind中:

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

如何显示图像而不是“ [] Byte Array”?

您可以使用以下方法获取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