2012-10-28 41 views
0

我剛學會了3個月的Visual Studio 2010 C#。我添加了數據源調用「PUBS.MDF」,這是來自Microsoft的示例數據庫,如「NORTHWIND.MDF」。並寫代碼到數據源用下面的代碼連接:應用程序無法與MDF文件建立連接,甚至無法成功構建項目[Visual Studio 2010 C#]

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Data.SqlClient; 

namespace WindowsFormsApplication18 
{ 
public partial class Form1 : Form 
    { 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     string constr = @"Data Source=.\SQLEXPRESS; 
         AttachDbFilename=|DataDirectory|\PUBS.mdf; 
         Integrated Security=True;User Instance=True;"; 
     SqlConnection connection = new SqlConnection(constr); 
     connection.Open(); 
     string sql = "SELECT * FROM authors"; 
     SqlCommand command = new SqlCommand(sql, connection); 
     textBox1.Text = (string)command.ExecuteScalar(); 
    } 

    } 
} 

此代碼調試成功,如下圖:

不過,我建立了項目後,安裝在我的電腦( window7),點擊打開應用程序(我也點擊「以管理員身份運行」),它顯示如下圖所示的錯誤窗口:

有人請幫助我。

PS。

這是我如何添加PUBS.MDF文件在我的應用

  1. 點擊選項卡「數據」
  2. 點擊「添加新數據周守軍......」
  3. 選擇「數據庫」
  4. 選擇 「數據集」
  5. 瀏覽 「PUBS.MDF」 文件

我這是怎麼建項目

  1. 點擊選項卡 「文件」>添加>新建項目> Visual Studio安裝>安裝項目
  2. 右鍵單擊 「應用程序文件夾」> 「添加」> 「項目輸出」> 「主輸出」
  3. 右鍵單擊「應用程序文件夾」>「添加」>「文件...」>瀏覽「PUBS.MDF」文件
  4. 在「解決方案資源管理器」窗口中,右鍵單擊項目名稱>單擊「生成」並等待顯示消息「Build secceed」

我也上傳了項目,請通過此鏈接下載 - >http://www.4shared.com/zip/-HLqC-b_/WindowsFormsApplication18.html

我以前用這個問題差不多 - >Building project succeed with Access database, can search the data but cannot delete the record但在這種情況下,數據庫是.accdb文件,可以通過點擊「以管理員身份運行」來解決,但這種情況是.MDF文件我不知道爲什麼只是不同類型的數據庫文件,但不能用相同的方法解決。

回答

2

更改您的連接字符串如下。它可能工作:

 string constr [email protected]"Data Source=.\SQLEXPRESS;AttachDbFilename=" + System.Windows.Forms.Application.StartupPath + "\\PUBS.mdf;Integrated Security=True;User Instance=True"; 
+0

對不起,我嘗試作爲你的建議,但它不工作,仍然錯誤。 – bemygon