I am new to c# asp.net. got this code from a tutorial but I am getting an error. My label says log in failed though I entered the correct data. Please help me :( and it says: Object reference not set to an instance of an object when I entered an incorrect data.
here's my ConnectionClass.cs
public class ConnectionClass
{
private static SqlConnection conn;
private static SqlCommand command;
static ConnectionClass()
{
string connectionString = ConfigurationManager.ConnectionStrings["CoffeeDBConnectionString"].ToString();
conn = new SqlConnection(connectionString);
command = new SqlCommand("", conn);
}
public static User LoginUser(string login, string password)
{
//Check if user exists
string query = string.Format("SELECT COUNT(*) FROM SkyMusic.dbo.user WHERE username = '{0}'", login);
command.CommandText = query;
try
{
conn.Open();
int numofUsers = (int) command.ExecuteScalar();
if (numofUsers < 1)
{
//user exists, check if the passwords match
query = string.Format("SELECT password FROM user WHERE username = '{0}'", login);
command.CommandText = query;
string dbPassword = command.ExecuteScalar().ToString();
if (dbPassword == password)
{
//Passwords match
query = string.Format("SELECT email, user_type FROM users WHERE username = '{0}'", login);
command.CommandText = query;
SqlDataReader reader = command.ExecuteReader();
User user = null;
while (reader.Read())
{
string email = reader.GetString(0);
string type = reader.GetString(1);
user = new User(login, password, email, type);
}
return user;
}
else
{
//passwords do not match
return null;
}
}
else
{
return null;
}
}
finally
{
conn.Close();
}
}
my login:
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div id="formcont">
<table>
<tr>
<td><asp:Label ID="Label1" runat="server" Text="Username:"></asp:Label></td>
<td><asp:TextBox ID="TextBox1" runat="server" Width="142px"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="Label2" runat="server" Text="Password:"></asp:Label></td>
<td><asp:TextBox ID="TextBox2" runat="server" Width="142px"></asp:TextBox></td>
</tr>
<tr>
<td colspan="2"></br><asp:Button ID="Button1" runat="server" Text="Log In" />
<br />
</td>
</tr>
</table>
<p>Don't have an account? Click <a href="Register.aspx" runat="server">here</a>!</p>
</div>
</asp:Content>
and
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
User user = ConnectionClass.LoginUser(txtUname.Text, txtPass.Text);
if (user != null)
{
Session["login"] = user.login;
Session["type"] = user.type;
Response.Redirect("Home.aspx");
}
else
{
lblError.Text = "Login Failed";
}
}
please help :( here's my db id, username, password, email, user_type