【问题标题】:Cannot connect to Sql server due to NullReferenceException [duplicate]由于 NullReferenceException 无法连接到 Sql 服务器 [重复]
【发布时间】:2014-03-19 12:40:51
【问题描述】:

我有一个以登录表单开头的 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 进行连接之前 我在 Management Studio 中使用 Sql server 2008 r2 我最初收到了 Failed to connect to the default database 疑点-> 是不是因为在一个应用程序中使用了两种不同类型的数据库而导致的问题 我尝试重新安装 sql server 2008 但没有用 请帮忙

【问题讨论】:

  • 抛出异常的哪一行以及该行上的哪个引用为空?我猜你在名为 ConnectionStringFMS 的配置文件中没有连接字符串,但这只是一个猜测。
  • @jmcilhinney 这是我在配置文件中的参考
  • NullReferenceException 的几乎所有情况都是相同的。请参阅“What is a NullReferenceException in .NET?”获取一些提示。
  • @JohnSaunders 那么在我的情况下我应该怎么做?我有点迷茫,请指导我!谢谢
  • 学习使用调试器。找出哪些数据为空,然后找出它为空的原因,然后修复它

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


【解决方案1】:

将您的连接字符串放入 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 2018-11-27
    • 1970-01-01
    • 2020-11-21
    • 2018-11-07
    • 2019-10-30
    • 1970-01-01
    相关资源
    最近更新 更多