2016-04-25 91 views
0

所以,我有一個類多數民衆贊成在進口數據從數據庫到我的應用程序:C#WPF圖像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; 
    } 

如何顯示圖像,而不是「[]字節數組」?

回答

0

您可以通過使用得到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; 
     } 
    } 
+0

謝謝您的回答,但我如何選擇我的數據網格時,其動態創建bitmapBytes? – xoghas