2

下面是 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 浏览图像时,数据源中指定的路径会更改为浏览的图像文件的路径,从而引发找不到数据库的异常。

需要进行适当更改的建议。

4

1 回答 1

0

一个快速而肮脏的解决方案是将RestoreDirectory设置为 true:

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

更好的解决方案是避免在连接字符串中使用相对路径,例如

  • 使用 |数据目录| 在您的连接字符串中

  • AppDomain.CurrentDomain.SetData("DataDirectory", somepath)在应用程序启动时调用以设置 |DataDirectory| 引用的位置。例如,您可以将其设置为包含可执行文件的目录,如下所示:

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

顺便说一句,OpenFileDialogimplements IDisposable,所以你真的应该调用IDisposable.Dispose,可能有一个using声明:

using (OpenFileDialog oBrowseImageFile = new OpenFileDialog())
{
    oBrowseImageFile.Filter = ...
    ... etc ...
}
于 2012-12-04T10:08:30.670 回答