簡體   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