由于NullReferenceException,无法连接到Sql服务器

时间:2014-03-19 04:30:19

标签: c# sql winforms sql-server-2008 nullreferenceexception

我有一个以登录表单开头的Windows窗体应用程序 登录表格在过去几天一直很好,而我正在处理剩余的应用程序 我现在得到一个错误 我有两个数据库一个DB.mdf和一个MYD.sdf

  

NullReferenceException未处理

     

对象引用未设置为对象的实例。

这段特殊代码--->

private void button1_Click(object sender, EventArgs e)
    {
        string path=@"C:\Users\Srinath\Documents\Visual Studio 2010\Projects\TESTFEE\TESTFEE\DB.mdf";
SqlConnection con =new SqlConnection(@"Data Source=.\SQLEXPRESS; AttachDbFilename='"+path+"';User Instance=True");

            string constring=ConfigurationManager.ConnectionStrings["ConnectionStringFMS"].ConnectionString;
         //SqlConnection con=new SqlConnection(constring);

        SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from LOGIN where USERNAME='" + textUser.Text + "' and PASSWORD='" + textPass.Text + "'", con);
        DataTable dt = new DataTable();

        try
        {
            sda.Fill(dt);
            if (dt.Rows[0][0].ToString() == "1")
            {
                this.Hide();
                e1.Show();

            }
            else
            {

                HoldButton();
                MessageBox.Show("Please Enter Your Right Credentials");
            }

        }
        catch (SqlException ex)
        {

            MessageBox.Show(ex.Message);
        }




        }//![The error i get ][1 -]

我尝试使用配置文件连接字符串 在我直接使用SqlConnection进行连接之前 我在管理工作室使用Sql server 2008 r2 我首先收到了初始连接到默认数据库的失败 怀疑 - > 这是问题,因为在一个应用程序中使用两种不同类型的db 我尝试重新安装sql server 2008但没有用 请帮忙

1 个答案:

答案 0 :(得分:0)

将您的连接字符串放在webconfig中,如果您将* .mdf放在App_Data文件夹中,则使用此格式

<connectionStrings>
  <add name="ConnectionName"
    connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True"
    providerName="System.Data.SqlClient" />
</connectionStrings>