I done login form in c# using login control. It gives runtime error near while loop.

error-'Invalid attempt to Read when reader is closed.'

Please give me solution bcoz i tried many options here.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
bool Autheticated = false;
Autheticated = SiteLevelCustomAutheticationMethod(Login1.UserName, Login1.Password);
e.Authenticated = Autheticated;
if (Autheticated == true)

private bool SiteLevelCustomAutheticationMethod (string UserName,string Password)
bool boolReturnValue = false;
string scon = "SERVER=.; INITIAL CATALOG=Villaplus; UID=sa; PWD=ash; ";
SqlConnection con = new SqlConnection(scon);
string strSQL = "Select * From Login";
SqlCommand com = new SqlCommand(strSQL, con);
SqlDataReader Dr;
Dr = com.ExecuteReader();
while (Dr.Read())
if ((UserName == Dr["Uname"].ToString()) & (Password == Dr["Pwd"].ToString()))
boolReturnValue = true;

return boolReturnValue;


My guess is that perhaps the information used to connect to the SQL server may be incorrect, and so its not actually establishing a connection. Also, to prevent the application from quitting, wrap the while loop in a try-catch block.

You have the close inside the read loop. Move it outside the loop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.