-4
public MyUniversity GetDepartmentsByDepartmentID(string department)
{
    string query = "SELECT * FROM Departments WHERE DepartmentID ='" + department + "'";
    SqlConnection connection = new SqlConnection(dbConnection);

    SqlCommand command = new SqlCommand(query, connection);

    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    MyUniversity deprtmnt = new MyUniversity();
    while (reader.Read())
    {
        deprtmnt.code = reader["Code"].ToString();
        deprtmnt.title = reader["title"].ToString();
        deprtmnt.credit = reader["Credit"].ToString();
        deprtmnt.description = reader["Description"].ToString();
        deprtmnt.semester = reader["Semester"].ToString();


        reader.Close();
        connection.Close();
        return deprtmnt;
    }
}
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
sam sam
  • 13
  • 4
  • 1
    This is an incomplete question; Please fix your code formatting and provide an explanation of what you're trying to do. – Soviut Apr 30 '17 at 07:52

1 Answers1

2

Your error is that not all code path return value. Reason is that in the scope of your loop:

while (reader.Read())
{
    /* Code */
    return deprtmnt;
}

If code doesn't enter while loop then there is no return statement. move the return to be outside of the loop's scope:

MyUniversity deprtmnt = new MyUniversity();
while (reader.Read())
{
    /* Code */
}
return deprtmnt;

Read about parameterized queries as using string concatenation for sql queries is susceptible for sql-injections

Community
  • 1
  • 1
Gilad Green
  • 36,708
  • 7
  • 61
  • 95