0

I tried the following in SQL Server Management Studio; I can connect and run query, but not from my project

string s = "Server=LAPTOP-7J47C5JA\SQLEXPRESS;Database=Test;Trusted_Connection=True;";

string queryString =   "SELECT * from tbclienti";

cn = new SQLConnection(s);

// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, cn);

cn.Open();

SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
{
    Text = reader[0].ToString();
    label1.Text = reader[1].ToString()+ " " + reader[2].ToString();
}

reader.Close();
cn.Close();
7
  • 1
    what exactly happens, any error ? Commented Apr 8, 2018 at 10:15
  • it comes a window with a list of processes., It'not proerly an an error Commented Apr 8, 2018 at 10:19
  • Lets try first connection string. Is it connecting to db ? string s = @"Server=(local)\SQLEXPRESS;Database=Test;Integated Security=SSPI;"; Commented Apr 8, 2018 at 10:26
  • using(SqlConnection cn = new SqlConnection(s)) { try { cn.Open(); }catch(Exception ex) { } } Commented Apr 8, 2018 at 10:28
  • it gives error the name cn does not exist in the context windowsfromapp2 Commented Apr 8, 2018 at 10:36

1 Answer 1

2

I posted here whole code what could look like. Try it now.

    string s = @"Server=(local)\SQLEXPRESS;Database=Test;Integrated Security=SSPI;";

    using(SqlConnection cn = new SqlConnection(s))
    {
        string queryString = "SELECT * from tbclienti";

        try
        {    
          cn.Open();
          // Create the Command and Parameter objects.
          SqlCommand command = new SqlCommand(queryString, cn);
          SqlDataReader reader = command.ExecuteReader();
          while (reader.Read())
          {
             Text = reader[0].ToString();
             label1.Text = reader[1].ToString()+ " " + reader[2].ToString();

           }
           reader.Close();
         }
         catch(Exception ex) 
         {
             // see if error appear
         }
         finally
         {
           cn.Close();
         }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

THANKS NOW IT WORKS: i ONLY ADDED @ IN FRONT OF THE CONNECTION STRING
Ah those backslashes :). Im glad it worked. If you dont put @ you need two backslashes like \\

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.