F 505
F 505

Reputation: 414

How can I handle this error?

I'm a new developer with c#, I created a c# project and I need to access the SQL database to perform the SELECT statement

and I got this error in this figure

enter image description here

My connection statement is correct, so what's wrong with it ?!

I tried the mentioned solutions and I got this error

enter image description here

does anyone know how to handle it ?!

Upvotes: 1

Views: 81

Answers (2)

Suraj Singh
Suraj Singh

Reputation: 4069

Reader needs open connection

Put con.Open() before executing reader

SqlCommand cmd = newSqlCommand("SELECT EmpName from Employee where EmpID =" +id.Text,con);
con.open(); //Open connection
SqlReader Read = cmd.ExecuteReader();
if (Read.Read())
{
 Position =Read[0].tostring();
}
read.close();
con.close();//Close connection after reader finishes reading
con.Dispose();

Upvotes: 2

Habib
Habib

Reputation: 223277

The error is telling you what to do, your connection is not open yet. Open it like:

con.Open();

Before executing your command.

Couple of things for your code, Use parameterized query, this will save you from SQL Injection, also use using statement which will ensure disposal of connection object.

using (SqlConnection con = new SqlConnection("connection string")) 
using(SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID=@EmpID", con))
{
    cmd.Parameters.AddWithValue("@EmpID", id.Text);
    con.Open();
    SqlDataReader reader = cmd.ExecuteReader();
    //..... your rest of the code
}

EDIT:

For your edited part of question, you are having issue with your SQL Server not allowing remote connection. You have to enable it.

See: How to enable remote connections in SQL Server

Upvotes: 6

Related Questions