Sunday, April 17, 2011

Database Basics using C#:


The following demonstrates a Register Page where the user is allowed to register, by entering a username and password. These inputs are saved in a table in database and later verified when user wants to login using the login page.

Section I:
Code for Register Page

    String ConnString = “--Your Connection_String goes here--";
    SqlConnection con = new SqlConnection(ConnString);

    String Command = ”insert into TABLE_NAME values(@username,@password)”;
    SqlCommand cmd = new SqlCommand(command, con);

    con.Open();

    cmd.Parameters.Add(“@username”, SqlDbType.Text).Value = Textusername.Text;
    cmd.Parameters.Add(“@password”, SqlDbType.Text).Value = Textpassword.Text;

    int a = cmd.ExecuteNonQuery();

    if (a > 0)
    {
        Response.Redirect(“~/Login.aspx”);
    }
    else
    {
        lablel.ForeColor = System.Drawing.Color.Red;
        label.Text = “Error Occured!”;
    }

Section II:
Code for Login Page


SqlConnection con = new SqlConnection(connString);
SqlDataAdapter da = new SqlDataAdapter(“select * from userinfo”, con);
DataSet ds = new DataSet();
da.Fill(ds, “info”);

string username = Textusername.Text;
string password = Textpassword.Text;

int find = 0;
foreach (DataRow dr in ds.Tables["info"].Rows)
{
    if (username == dr["username"].ToString())
    {
        if (password == dr["password"].ToString())
        {
        find = 1;
        break;
        } // end of 1st if
    }// end of 2nd if
} // end of for each

if (find == 1)
{
    Response.Redirect(“~/Home.aspx”);
}
else
{
    Labelerror.ForeColor = System.Drawing.Color.Red;
    Labelerror.Text = “Username Password Mismatch”;
}



0 comments:

Post a Comment

 

2011 ·Code-Studio by yrus.