2012-12-04 49 views
2

下面是app.config文件中的連接字符串。注意數據源中指定的路徑。當瀏覽圖片時,App.config中的連接字符串發生變化

<?xml version="1.0"?> 
<configuration> 
    <connectionStrings> 
    <add name="ConnString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\..\Database\ProductsDatabase.accdb;Persist Security Info=False;" providerName="System.Data.SqlClient"/> 
    </connectionStrings> 
</configuration> 

該應用程序具有一個帶有MouseDoubleclick事件的按鈕控件內的圖像控件。

     <Button Name="m_oBtnProductImage" Grid.Column="0" Height="60" Width="60" Background="LightGray" Style="{x:Null}" MouseDoubleClick="m_oBtnProductImage_MouseDoubleClick"> 
           <Image Tag="Image" Name="m_oImage" Stretch="Fill" Source="{Binding SelectedProductEn.ProductImage}"></Image> 
         </Button> 

MouseDoubleClick事件處理程序具有以下功能:瀏覽和上傳新的圖片,比更新數據庫中的相同。

private void m_oBtnProductImage_MouseDoubleClick(object sender, RoutedEventArgs e) 
    { 
     Bitmap oBitmapImage = null; 
     OpenFileDialog oBrowseImageFile = new OpenFileDialog(); 
     oBrowseImageFile.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp"; 
     if (oBrowseImageFile.ShowDialog() == true) 
     { 
      System.Windows.Controls.Image oPictureBox = ((Button)sender).FindName("m_oImage") as System.Windows.Controls.Image; 
      string sImagePath = oBrowseImageFile.FileName; 
      oBitmapImage = new Bitmap(sImagePath); 
      ((CMainUIViewModel)this.DataContext).SelectedProductEn.ProductImage = (byte[])TypeDescriptor.GetConverter(oBitmapImage).ConvertTo(oBitmapImage, typeof(byte[])); 
      ((CMainUIViewModel)this.DataContext).UpdateModifiedProduct(((CMainUIViewModel)this.DataContext).SelectedProductEn); 
     } 
    } 

當圖像被從應用程序的UI,在數據源更改瀏覽圖像文件的路徑指定的路徑瀏覽,從而拋出一個例外沒有找到數據庫。

需要做出適當修改的建議。

+1

您將需要準確顯示m_oBtnProductImage_MouseDoubleClick正在做什麼。 –

回答

0

一個快速和骯髒的解決辦法是設置RestoreDirectory爲true:

oBrowseImageFile.RestoreDirectory = true; 
if (oBrowseImageFile.ShowDialog()) 
{ 
    ... 
} 

更好的解決方案是避免連接字符串,例如在使用相對路徑

  • use | DataDirectory |在您的連接字符串中

  • 當您的應用程序啓動時設置由| DataDirectory |引用的位置時調用AppDomain.CurrentDomain.SetData("DataDirectory", somepath)。例如,可以按如下方式將其設置爲包含你可執行文件的目錄:

    AppDomain.CurrentDomain.SetData("DataDirectory", 
        AppDomain.CurrentDomain.BaseDirectory); 
    

順便說一句,OpenFileDialog實現IDisposable,所以你應該叫IDisposable.Dispose,大概有using聲明:

using (OpenFileDialog oBrowseImageFile = new OpenFileDialog()) 
{ 
    oBrowseImageFile.Filter = ... 
    ... etc ... 
} 
+0

@ Joe.it作品。使用| DataDirectory |在數據源中做到了。 – user1874589

相關問題