Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi my name is vishal i was wondering on how to make my global variable accept value from another table in c# windows forms with sql server 2008? So i have a application named:Mini Project,i also have login form named:frmLogin. Given below is it's c# code:
C#
namespace Mini_Project
{
    public partial class frmLogin : Form
    {
public frmLogin()
        {
            InitializeComponent();
        }
private void frmLogin_Load(object sender, EventArgs e)
        {
        }
 private bool ManagerUser(string username, string password)
        {
           bool success = false;
            SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Task;Integrated Security=true");
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd = new SqlCommand("Select * from [dbo].[ManagerDetail2] where username='"+txtUsername.Text+"' and password='"+txtPassword.Text+"' and LoginAttempts< 3", conn);
            SqlDataReader rd = cmd.ExecuteReader();
           while(rd.Read())
            {
                success=true;
                Module.MUser_ID = Convert.ToInt32(rd[0].ToString());
                Module.MUserName = rd[1].ToString();
            }
            rd.Close();
            conn.Close();
            return success;
        }
private bool ValidateUser(string username, string password)
        {
            bool success = false;
            SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Task;Integrated Security=true");
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd = new SqlCommand("Select * from [dbo].[UserDetail2] where username='"+txtUsername.Text+"' and password='"+txtPassword.Text+"' and LoginAttempts< 3", conn);
            SqlDataReader rd = cmd.ExecuteReader();
           while(rd.Read())
            {
                success=true;
                Module.User_ID = Convert.ToInt32(rd[0].ToString());
                Module.UserName = rd[1].ToString();
            }
            rd.Close();
            conn.Close();
            return success;
        }
private void btnLogin_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Task;Integrated Security=true");
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            if ((txtPassword.Text == "password") && (txtUsername.Text.ToLower() == "admin"))
            {
                Module.AUser_ID=1;
                MDIParent1 h = new MDIParent1();
                h.Show();
                this.Close();
            }
            else
            {
                string username = txtUsername.Text;
                string password = txtPassword.Text;
                bool validUser = ValidateUser(username, password);
                bool validmanager = ManagerUser(username, password);
                if (validUser)
                {
                    cmd = new SqlCommand("Update [dbo].[UserDetail2] set LoginAttempts=0 where username='" + txtUsername.Text + "'", conn);
                    cmd.ExecuteNonQuery();
                    Module.User_ID = 1;
                    MDIParent1 m = new MDIParent1();
                    m.Show();
                    this.Close();
                }
                     if (validmanager)
                    {
                        cmd = new SqlCommand("Update [dbo].[ManagerDetail2] set LoginAttempts=0 where username='" + txtUsername.Text + "'", conn);
                        cmd.ExecuteNonQuery();
                        Module.MUser_ID = 1;
                        MDIParent1 g = new MDIParent1();
                        g.Show();
                        this.Close();
                    }    
                    else
                    {
                        cmd = new SqlCommand("Update [dbo].[UserDetail2] set LoginAttempts=LoginAttempts+1 where username='" + txtUsername.Text + "'", conn);
                    cmd.ExecuteNonQuery();
                    cmd = new SqlCommand("Update [dbo].[ManagerDetail2] set LoginAttempts=LoginAttempts+1 where username='" + txtUsername.Text + "'", conn);
                    cmd.ExecuteNonQuery();
                        MessageBox.Show("Invalid user name or password. Please try tomorow ", "Task", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtUsername.Focus();
                    }
                }
            }
private void btnCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

The above code works OK! So using default username:admin and default password:password i login/enter into application as admin,then i create a new manager for tasks. Given below is my c# code of form(frmManager):
C#
namespace Mini_Project
{
    public partial class frmManager : Form
    {
public int bGenId = -1;
        public frmManager()
        {
            InitializeComponent();
        }
private void btnCreate_Click(object sender, EventArgs e)
        {
SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Task;Integrated Security=true");
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
cmd = new SqlCommand("Insert into [dbo].[ManagerDetail2](manager_first_name,manager_last_name,manager_dob,manager_sex,email,username,password,status,created_by,LoginAttempts,row_upd_date)" + "Values(@manager_first_name,@manager_last_name,@manager_dob,@manager_sex,@email,@username,@password,@status,@created_by,@LoginAttempts,GetDate()); Select @autoGenId=SCOPE_IDENTITY();", conn);
            cmd.Parameters.AddWithValue("@manager_first_name", txtFName.Text);
            cmd.Parameters.AddWithValue("@manager_last_name", txtLName.Text);
            cmd.Parameters.AddWithValue("@manager_dob", dtDOB.Value);
            if (cboSex.SelectedIndex == 0)
            {
                cmd.Parameters.AddWithValue("@manager_sex", "Male");
            }
            else if (cboSex.SelectedIndex == 1)
            {
                cmd.Parameters.AddWithValue("@manager_sex", "Female");
            }
            else if (cboSex.SelectedIndex == 2)
            {
                cmd.Parameters.AddWithValue("@manager_sex", "Transgender");
            }
            cmd.Parameters.AddWithValue("@email", txtEmailID.Text);
            cmd.Parameters.AddWithValue("@username", txtUsername.Text);
            cmd.Parameters.AddWithValue("@password", txtPassword.Text);
            cmd.Parameters.AddWithValue("@status", 1);
            cmd.Parameters.AddWithValue("@Created_by", 1);
            cmd.Parameters.AddWithValue("@LoginAttempts", 0);
            cmd.Parameters.Add("@autoGenId", SqlDbType.Int).Direction = ParameterDirection.Output;
            cmd.ExecuteNonQuery();
            bGenId = Convert.ToInt32(cmd.Parameters["@autoGenId"].Value);
            cmd = new SqlCommand("Update [dbo].[ManagerDetail2] set LoginAttempts=0 where username='" + txtUsername.Text + "'", conn);
            cmd.ExecuteNonQuery();
((MDIParent1)this.MdiParent).updateUserActivities(bGenId, 2, txtFName.Text.ToString() + "Manager detail was added successfully");
            MessageBox.Show("Manager Detail was added successfully", "Task", MessageBoxButtons.OK, MessageBoxIcon.Information);
            conn.Close();
            this.Close();
        }

The above code works fine! Given below is my structure of table named:ManagerDetail2 in sql server 2008 to which i insert values from form(frmManager):
ColumnName DataType AllowNulls
manager_id(auto-increment primary key) Int No
manager_first_name nvarchar(50) Yes
manager_last_name nvarchar(50) Yes
manager_dob date Yes
manager_sex nvarchar(20) Yes
email nvarchar(60) Yes
username nvarchar(25) Yes
password nvarchar(15) Yes
status bit Yes
created_by Int Yes
LoginAttempts Int Yes
row_upd_date datetime Yes

Using username and password from ManagerDetail2 i login/enter into application as a manager and create new users(normal user) who will come under me.Given below is c# code of form(frmUser):
C#
namespace Mini_Project
{
    public partial class frmUser : Form
    {
public int autoGenId = -1;
        public frmUser()
        {
            InitializeComponent();
        }
private void btnCreate_Click(object sender, EventArgs e)
        {
SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Task;Integrated Security=true");
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
cmd = new SqlCommand("Insert into [dbo].[UserDetail2](user_first_name,user_last_name,user_dob,user_sex,email,username,password,status,row_upd_date,created_by,LoginAttempts)" + "Values(@user_first_name,@user_last_name,@user_dob,@user_sex,@email,@username,@password,@status,GetDate(),@created_by,@LoginAttempts); Select @autoGenId=SCOPE_IDENTITY();", conn);
            cmd.Parameters.AddWithValue("@user_first_name", txtFName.Text);
            cmd.Parameters.AddWithValue("@user_last_name", txtLName.Text);
            cmd.Parameters.AddWithValue("@user_dob", dtDOB.Value);
            if (cboSex.SelectedIndex == 0)
            {
                cmd.Parameters.AddWithValue("@user_sex", "Male");
            }
            else if (cboSex.SelectedIndex == 1)
            {
                cmd.Parameters.AddWithValue("@user_sex", "Female");
            }
            else if (cboSex.SelectedIndex == 2)
            {
                cmd.Parameters.AddWithValue("@user_sex", "Transgender");
            }
            cmd.Parameters.AddWithValue("@email", txtEmailID.Text);
            cmd.Parameters.AddWithValue("@username", txtUsername.Text);
            cmd.Parameters.AddWithValue("@password", txtPassword.Text);
            cmd.Parameters.AddWithValue("@status", 1);
            cmd.Parameters.AddWithValue("@created_by",Module.Manager);
            cmd.Parameters.AddWithValue("@LoginAttempts", 0);
cmd.Parameters.Add("@autoGenId", SqlDbType.Int).Direction = ParameterDirection.Output;
            cmd.ExecuteNonQuery();
 autoGenId = Convert.ToInt32(cmd.Parameters["@autoGenId"].Value);
cmd = new SqlCommand("Update [dbo].[UserDetail2] set LoginAttempts=0 where username='" + txtUsername.Text + "'", conn);
            cmd.ExecuteNonQuery();
((MDIParent1)this.MdiParent).updateUserActivities(autoGenId, 1, txtFName.Text + "User detail was added successfully");
            MessageBox.Show("User Detail was added successfully", "Task", MessageBoxButtons.OK, MessageBoxIcon.Information);
            conn.Close();
            this.Close();
}

The above code works OK to some extent only! Given below is structure of table:UserDetail2 in sql server 2008 to which i insert values from form(frmUser):
ColumnName DataType AllowNulls
user_id(auto-increment primary key) Int No
user_first_name nvarchar(50) Yes
user_last_name nvarchar(50) Yes
user_dob date Yes
user_sex nvarchar(20) Yes
email nvarchar(60) Yes
username nvarchar(25) Yes
password nvarchar(15) Yes
status bit Yes
created_by Int Yes
LoginAttempts Int Yes
row_upd_date datetime Yes

Given below is my c# code of class named:Module
C#
namespace Mini_Project
{
    class Module
    {
        public static int AUser_ID;
        public static int Admin
        {
            get { return AUser_ID; }
            set { AUser_ID = value; }
        }
        public static int User_ID;
        public static int User
        {
            get { return User_ID; }
            set { User_ID = value; }
        }
        public static int MUser_ID;
        public static int Manager
        {
            get { return MUser_ID; }
            set { MUser_ID = value; }
        }
public static string UserName="";
        public static string GlobalUser
        {
            get { return UserName; }
            set { UserName = value; }
        }
        public static string MUserName="";
        public static string GlobalManager
        {
            get { return MUserName; }
            set { MUserName = value; }
        }
        public static string AUserName="";
        public static string GlobalAdmin
        {
            get { return AUserName; }
            set { AUserName = value; }
        }
    }

The above code works OK! to some extent only.
The problem i am facing is after entering into application as a manager and when i create a new user(normal user) under me i get value of 1 for all users in my field created_by in table:UserDetail2.
What i want is when i enter into application as a manager(using username and password from ManagerDetail) and based on my id(manager_id) of entered manager i should get the same value of manager_id value in my field created_by in table:UserDetail2.
But instead i am getting value 1 for all users and also in my field:created_by in table:UserDetail2.
Can anyone help me please!Can anyone help me/guide me to achieve my required result! Can anyone tell me what modifications must i need to do in my c# code and where!? Any help/guidance in solving of this problem would be greatly appreciated!
Posted
Comments
Suvendu Shekhar Giri 3-Jan-15 13:03pm    
This is a community site. Ask only about the problem or error you are getting. Please don't come with the complete project. Nobody has time to read so many lines of code.
If you want to get answer to your problem, it's better to be little more specific about your problem and provide only the portion or code snippet which is required to know. Then someone can help you.
Hopefully, you understand what I said.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900