Thursday, January 8, 2009

Basic example on login sequence and carrying data between forms: Welcome Marty McFly

Let's give a simple example on carrying data between forms by saying hi to our guest login star "mmcfly".

Let's micro manage for a second:
We have 1 user: "Marty McFly", who has the properties: "id, name, password" to login. So we need a database to keep his info and a class to define this info on our program.

We name the database: "myDatabase", name the table: "user" and columns:"userId, userName, userPassword".

Back to the code side, our "login" class keeps definitons:

private int userId;

public int UserId
{
get { return userId; }
set { userId = value; }
}
private string userName;

public string UserName
{
get { return userName; }
set { userName = value; }
}
private string userPassword;

public string UserPassword
{
get { return userPassword; }
set { userPassword = value; }
}


It's time to log Marty in.

We create an instance of the login class and fill it with Marty's information.

login logg= null;

private void button1_Click(object sender, EventArgs e)
{

SqlConnection con = new SqlConnection("server=.;database=myDatabase;uid=userId;pwd=password");

SqlCommand com = new SqlCommand("select userName, userPassword from login where userName=@userName and userPassword=@userPassword",con);

com.Parameters.AddWithValue("@userName", textBox1.Text);
com.Parameters.AddWithValue("@userPassword", textBox2.Text);

con.Open();

SqlDataReader dr = com.ExecuteReader();

while(dr.Read())
{
logg=new login();
logg.UserName = dr["userName"].ToString();
logg.UserPassword = dr["userPassword"].ToString();
}

con.Close();


We have just called the login information from database, matched it and wrote it on our instance of login class so we can use it anywhere we want.
If the info we have entered is true we can now use the information on another form:

private void frmChangePw_Load(object sender, EventArgs e)

{

label3.Text = (frmLogin.logg as login).userName;

}

which means in literal words: when loading this form, take the value of our "logg" instance from login class and use the "userName" property for the label's value.


You can carry any data you would need for your own scenario. In this one, Marty clicked on "mmcfly logged in" link and now he can change his password if he thinks "einstein" is too predictable for Doctor Brown.

No comments:

Post a Comment