Hi rakeshkuma,
You are getting this error because the SqlDataReader object does not have any column with the name UserId.
Check your Stored Procedure and make sure it returns UserId and Roles column.
Else to overcome this error you can check the column name with DataReader Fields and set the value.
Check the below code.
protected void ValidateUser(object sender, EventArgs e)
{
int userId = 0;
string roles = string.Empty;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Validate_User"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", Login1.UserName);
cmd.Parameters.AddWithValue("@Password", Login1.Password);
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
bool columnExist = false;
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader.GetName(i) == "UserId")
{
userId = Convert.ToInt32(reader["UserId"]);
columnExist = true;
break;
}
}
if (columnExist)
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader.GetName(i) == "Roles")
{
roles = reader["Roles"].ToString();
break;
}
}
}
con.Close();
}
switch (userId)
{
case -1:
Login1.FailureText = "Username and/or password is incorrect.";
break;
case -2:
Login1.FailureText = "Account has not been activated.";
break;
default:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Login1.UserName, DateTime.Now, DateTime.Now.AddMinutes(2880), Login1.RememberMeSet, roles, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, Login1.RememberMeSet));
break;
}
}
}