我能夠連接到我的網絡上的服務器上的數據庫,沒有任何問題。但是,當我嘗試使用SQL Server Express(本地數據庫)時,我不斷收到相同的錯誤。我創建了一個只有按鈕和標籤的新解決方案,以消除任何其他潛在問題。我已經擡起頭,嘗試幾乎每個場景在stackoverflow和谷歌無濟於事......我決定發佈一個問題,因爲我花了太多的時間在試圖解決這個問題。感謝您的任何方向使用c#asp.net連接到SQL Server Express數據庫
錯誤:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
DelWebApplication1.WebForm1.Button1_Click(Object sender, EventArgs e) in c:\Users\Rozelle\Documents\Visual Studio 2013\Projects\DelWebApplication1\DelWebApplication1\WebForm1.aspx.cs:23
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9628614
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724
C#代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data.Sql;
namespace DelWebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["MYConnectionString"].ToString();
SqlConnection conn = new SqlConnection(connectionString);
try
{
conn.Open();
Label1.Text = "Database Connected!!";
conn.Close();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
}
}
Web.Config中:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="DelWebApplication1.Properties.Settings.MyConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Rozelle\Documents\My.mdf;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
我建議你去尋找你的連接字符串,我相信有一些* fishy *連接字符串。 :-) –
我想你的配置文件中沒有名爲'MYConnectionString'的連接字符串。 –
是的,我想盡可能多,我嘗試了不同的字段的數據庫屬性:名稱,連接字符串等....,但仍然沒有成功 – suffa