Quantcast
Channel: Windows Forms Data Controls and Databinding forum
Viewing all articles
Browse latest Browse all 2535

how to have list of items present in listbox created by that user only when that same user enters/logs into the application and goes to that same form in c# windows forms with sql server 2008

$
0
0

Hi my name is vishal for 10 days i have been breaking my head on how to have a list ofitems in a listbox created by that user in  in c# windows forms and same user who has entered into the application and entered into form in c# windows forms with sql server 2008.

So given below is my c# code of frmLogin(login form):

namespace Mini_Project
{
    public partial class frmLogin : Form
    {
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");
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd = new SqlCommand("Select @count = Count(*) from [dbo].[ManagerDetail2] where username=@username and password=@password and LoginAttempts< 3", conn);
            cmd.Parameters.AddWithValue("@username", txtUsername.Text);
            cmd.Parameters.AddWithValue("@password", txtPassword.Text);
            cmd.Parameters.AddWithValue("@manager_id", Module.MUser_ID);
            cmd.Parameters.Add("@count", SqlDbType.Int).Direction = ParameterDirection.Output;
            conn.Open();
            cmd.ExecuteNonQuery();
            if (Convert.ToInt32(cmd.Parameters["@count"].Value)>0)
            {
                success = true;
                cmd = new SqlCommand("Update [dbo].[ManagerDetail2] set LoginAttempts=0 where username='" + txtUsername.Text + "'", conn);
                cmd.ExecuteNonQuery();
            }
            else
            {
                success = false;
                cmd = new SqlCommand("Update [dbo].[ManagerDetail2] set LoginAttempts=LoginAttempts+1 where username='" + txtUsername.Text + "'", conn);
                cmd.ExecuteNonQuery();
            }
            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");
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd = new SqlCommand("Select @count = Count(*) from [dbo].[UserDetail2] where username=@username and password=@password and LoginAttempts< 3", conn);
            cmd.Parameters.AddWithValue("@username", txtUsername.Text);
            cmd.Parameters.AddWithValue("@password", txtPassword.Text);
            cmd.Parameters.AddWithValue("@user_id", Module.User_ID);
            cmd.Parameters.Add("@count", SqlDbType.Int).Direction = ParameterDirection.Output;
            conn.Open();
            cmd.ExecuteNonQuery();
            if (Convert.ToInt32(cmd.Parameters["@count"].Value)>0)
            {
                success = true;
                cmd = new SqlCommand("Update [dbo].[UserDetail2] set LoginAttempts=0 where username='" + txtUsername.Text + "'", conn);
                cmd.ExecuteNonQuery();
            }
            else
            {
                success = false;
                cmd = new SqlCommand("Update [dbo].[UserDetail2] set LoginAttempts=LoginAttempts+1 where username='" + txtUsername.Text + "'", conn);
                cmd.ExecuteNonQuery();
            }
            conn.Close();
            return success;
        }
private void btnLogin_Click(object sender, EventArgs e)
        {
            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)
                    {
                        Module.User_ID = 1;
                        MDIParent1 m = new MDIParent1();
                        m.Show();
                        this.Close();
                    }
                     if (validmanager)
                    {
                        Module.MUser_ID = 1;
                        MDIParent1 g = new MDIParent1();
                        g.Show();
                        this.Close();
                    }
                    else
                    {
                        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 Fine! So i login into my application(Mini Project) using default username:admin and default passsword:password.

Given below is my c# code of how i add normal user(frmUser) into application:

namespace Mini_Project
{
    public partial class frmUser : Form
    {
 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;
            int autoGenId = -1;
            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.MUser_ID);
            cmd.Parameters.AddWithValue("@LoginAttempts", 0);
            cmd.Parameters.Add("@autoGenId", SqlDbType.Int).Direction = ParameterDirection.Output;
            cmd.ExecuteNonQuery();
            autoGenId = Convert.ToInt32(cmd.Parameters["@autoGenId"].Value);
            PuserID = 1;
            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 !

Given below is my structure of table named:UserDetail2 in sql server 2008:

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(80)                                                       Yes

username                                                  nvarchar(25)                                                       Yes

password                                                   nvarchar(15)                                                       Yes

status                                                            bit                                                                   Yes

row_upd_date                                          datetime                                                              Yes

created_by                                                    Int                                                                    Yes

LoginAttempts                                               Int                                                                    Yes

Given below is my c# code of how i add managers(frmManager) into my application:

using System.Data.SqlClient;
namespace Mini_Project
{
    public partial class frmManager : Form
    {
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;
             int bGenId = -1;
            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 structure of my table:ManagerDetail2 in sql server 2008

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(80)                                          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  how i assign a task to user created by a manager(frmTask):

 private void frmTask_Load(object sender, EventArgs e)
        {
            dtAssignDate.MinDate = dtAssignDate.Value;
            string user=("Select u.user_id as user_id,(u.user_first_name+' '+u.user_last_name+'|'+right('000'+convert(varchar,u.user_id),5)) as Name from UserDetail2 u  where u.status=1");
            DataTable mt = new DataTable();
            SqlConnection cont = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Task;Integrated Security=true");
            if (cont.State != ConnectionState.Open)
            {
                cont.Open();
            }
            SqlCommand hcr = new SqlCommand(user, cont);
            mt.Load(hcr.ExecuteReader());
            lstUsers.DataSource = mt;
            lstUsers.ValueMember = "user_id";
            lstUsers.DisplayMember = "Name";
            lstUsers.SelectedValue = 0;
        }

The above code works only to some extent!

The problem i am facing in above code is that i get all users in my listbox from table(UserDetail2) in c# windows forms with sql server 2008.

So i login/enter into my application(Mini Project)(using username and password from ManagerDetail2) ,add new user to application.

What i want is when that manager goes into frmTask then i want theusers created by that manager only to be displayed in my listbox(lstUsers) in my form(frmTask) once myfrmTasks loads that is what i want.

Given below is my c# code of my MdiParent(MDIParent1):

 private void MDIParent1_Load(object sender, EventArgs e)
        {
            connBuilder = new SqlConnectionStringBuilder();
            connBuilder.InitialCatalog = "DRRS";
            connBuilder.DataSource = "NPD-4\\SQLEXPRESS";
            connBuilder.IntegratedSecurity = true;
            connBuilder.AsynchronousProcessing = true;
            conn = new SqlConnection(connBuilder.ToString());
            conn.Open();
}
namespace Mini_Project
{
    public partial class MDIParent1 : Form
    {
        private int childFormNumber = 0;

        static int AUser_ID = 0;
        static int User_ID = 0;
        static int MUser_ID = 0;
        int pUserID;
        public MDIParent1()
        {
            InitializeComponent();
            if (Module.AUser_ID == 1)
            {
                addNewTaskToolStripMenuItem.Enabled = true;
                addUserToolStripMenuItem1.Enabled = true;
                addManagerToolStripMenuItem.Enabled = true;
                addTaskToolStripMenuItem.Enabled = true;
                exitToolStripMenuItem.Enabled = true;
                checkInUserToolStripMenuItem.Enabled = false;
                tasksToolStripMenuItem.Enabled = true;
                optionsToolStripMenuItem.Enabled = true;
                pendingTaksToolStripMenuItem.Enabled = true;
                completedTasksToolStripMenuItem.Enabled = true;
            }
            if (Module.MUser_ID == 1)
            {
                addUserToolStripMenuItem1.Enabled = false;
                addManagerToolStripMenuItem.Enabled = true;
                addNewTaskToolStripMenuItem.Enabled = false;
                addTaskToolStripMenuItem.Enabled = true;
                exitToolStripMenuItem.Enabled = true;
                checkInUserToolStripMenuItem.Enabled = false;
                tasksToolStripMenuItem.Enabled = true;
                optionsToolStripMenuItem.Enabled = true;
                pendingTaksToolStripMenuItem.Enabled = true;
                completedTasksToolStripMenuItem.Enabled = true;
            }
            if (Module.User_ID == 1)
            {
                addManagerToolStripMenuItem.Enabled = false;
                addUserToolStripMenuItem1.Enabled = false;
                addNewTaskToolStripMenuItem.Enabled = false;
                addTaskToolStripMenuItem.Enabled = false;
                exitToolStripMenuItem.Enabled = true;
                checkInUserToolStripMenuItem.Enabled = true;
                tasksToolStripMenuItem.Enabled = false;
                optionsToolStripMenuItem.Enabled = false;
                pendingTaksToolStripMenuItem.Enabled = false;
                completedTasksToolStripMenuItem.Enabled = false;
            }
        }

Given below is c# code of my class(Module):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mini_Project
{
    class Module
    {
        public static int AUser_ID=0;
        public static int User_ID=0;
        public static int MUser_ID=0;
    }
}

Can anyone help me Please! Can anyone tell me what modifications must i do in my c# code and where? Can anyone help me/guide me to achieve my required result?! Any help/guidance in solving of this problem would be greatly appreciated!


vishal




Viewing all articles
Browse latest Browse all 2535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>