The stability of the flow under the magnetic force is one of the classical problems in fluid mechanics. In this paper, the flow in a rectangular duct with different Hartmann $(Ha)$ number is simulated. The finite volume method and the SIMPLE algorithm are used to solve a system of equations and the energy gradient theory is then used to study the (associated) stability of magnetohydrodynamics (MHD). According to the energy gradient theory, $K$ represents the ratio of energy gradient in transverse direction and the energy loss due to viscosity in streamline direction. Position with large $K$ will lose its stability earlier than that with small $K$. The flow stability of MHD flow for different Hartmann $(Ha)$ number, from $Ha=1$ to 40, at the fixed Reynolds number, $Re=190$ are investigated. The simulation is validated firstly against the simulation in literature. The results show that, with the increasing Ha number, the centerline velocity of the rectangular duct with MHD flow decreases and the absolute value of the gradient of total mechanical energy along the streamwise direction increases. The maximum of $K$ appears near the wall in both coordinate axis of the duct. According to the energy gradient theory, this position of the maximum of $K$ would initiate flow instability (if any) than the other positions. The higher the Hartmann number is, the smaller the $K$ value becomes, which means that the fluid becomes more stable in the presence of higher magnetic force. As the Hartmann number increases, the $K$ value in the parallel layer decreases more significantly than in the Hartmann layer. The most dangerous position of instability tends to migrate towards wall of the duct as the Hartmann number increases. Thus, with the energy gradient theory, the stability or instability in the rectangular duct can be controlled by modulating the magnetic force.