Search code examples
c#asp.netsql-server-2008r2-express

asp.net cannot open database login failed


I'm using the following to retrieve data from a database but the SqlConnection won't open. It throws an error at scon.Open(). I'm sure it's elementary but I can't work it out.

protected void Page_Load(object sender, EventArgs e) {   
    SqlConnection scon = new SqlConnection("Data Source = .\\SQLEXPRESS; Database = populate.mdf; Integrated Security = true; Initial Catalog = populate");   

    StringBuilder htmlString = new StringBuilder(); 

    if(!IsPostBack)
    {
        using (SqlCommand scmd = new SqlCommand())
        {
            scmd.Connection = scon;
            scmd.CommandType = CommandType.Text;
            scmd.CommandText = "SELECT * FROM populate";

            scon.Open();

            SqlDataReader articleReader = scmd.ExecuteReader();

            htmlString.Append("'Populate page:'");                

            if (articleReader.HasRows)
            {
                while (articleReader.Read())
                {
                    htmlString.Append(articleReader["dateTime"]);
                    htmlString.Append(articleReader["firstName"]);
                    htmlString.Append(articleReader["lastName"]);
                    htmlString.Append(articleReader["address"]);
                    htmlString.Append(articleReader["details"]);
                }

                populatePlaceHolder.Controls.Add(new Literal { Text = htmlString.ToString() });
                articleReader.Close();
                articleReader.Dispose();
            }
        }
    }
}

I'm using this link https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx as one of my references. I'm also using SQL Server 2008 R2 Express if these information are of any help.

Here's part of the error message:

SqlException (0x80131904): Cannot open database "populate" requested by the login. The login failed.

Any help would be greatly appreciated.


Solution

  • I solved it. All the connection string and other code was correct. The database just needed connecting to the Management Studio with some extra attention.