Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
I had made an EmployeeMaster Application by using Datatable, datasets and datagrids but now i want to make the same using Generic Collections, so can anybody help me?

I want to have complete converted code for my code....
Following is mine code for EmployeeMaster...

Form1.cs


C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace EmployeeMaster
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        
        DataTable dt1;        
        string EmpID = "";
        SqlDataAdapter da = new SqlDataAdapter();
        SqlConnection con = new SqlConnection();
        string DepartmentID = "";        
        private void btnNewRecord_Click(object sender, EventArgs e)
        {
            comboBox1.SelectedIndex = 0;
            comboBox2.SelectedIndex = 0;
            textBox1.Clear();
            textBox1.Visible = false;
            label2.Visible = false;
            textBox2.Clear();
            textBox3.Clear();
            textBox4.Clear();            
            textBox6.Clear();
            textBox7.Clear();
            textBox8.Clear();            
            textBox2.ReadOnly = false;
            textBox2.Enabled = true;
            date1.Enabled = true;
            textBox6.ReadOnly = false;
            textBox7.ReadOnly = false;
            textBox8.ReadOnly = false;
            textBox6.Enabled = true;
            textBox7.Enabled = true;
            textBox8.Enabled = true;
            errorProvider1.Dispose();
            btnUpdate.Enabled = true;
            date1.Format = DateTimePickerFormat.Custom;            
            date1.Value = DateTime.Now;
            textBox2.Focus();
            if (btnUpdate.Text == "Update")
            {
                btnUpdate.Text = "Save"; 
            }            
        }
        private void run()
        {
            dt1 = new DataTable();
            EmpMaster get = new EmpMaster();
            dt1= get.Get();
            dataGridView1.DataSource = dt1;                       
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Visible = false;
            label2.Visible = false;
            run();
            EmpMaster getemptype = new EmpMaster();
            dt1 = getemptype.GetEmpType();
            comboBox1.DisplayMember = "EmploymentType";
            comboBox1.ValueMember = "EmpType_ID";
            comboBox1.DataSource = dt1;            

            EmpMaster getdept = new EmpMaster();
            dt1 = getdept.GetDept();
            comboBox2.DisplayMember = "departmentname";
            comboBox2.ValueMember = "departmentid";
            comboBox2.DataSource = dt1;
            btnUpdate.Enabled = false;
            comboBox1.SelectedIndex = 0;
            comboBox2.SelectedIndex = 0;
            textBox3.Clear();
            textBox4.Clear();
            textBox2.Focus();
        }
        private void dataGridView1_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            textBox1.Visible = true;
            label2.Visible = true;
            textBox2.Enabled = true;
            btnUpdate.Enabled = true;
            int xyz = e.RowIndex;
            DataRowView dr = (DataRowView)dataGridView1.Rows[xyz].DataBoundItem;
            EmpID = dr["EmpID"].ToString();
            DepartmentID = dr["DepartmentID"].ToString();
            textBox1.Text = dr["EmpID"].ToString();
            textBox2.Text = dr["EmpName"].ToString();            
            comboBox1.SelectedValue = dr["EmpType_ID"].ToString();
            comboBox2.SelectedValue = dr["DepartmentID"].ToString();
            date1.Format = DateTimePickerFormat.Short;
            date1.Value = Convert.ToDateTime( dr["DateofJoining"]);
            textBox6.Text = dr["GrossSalary"].ToString();
            textBox7.Text = dr["NetSalary"].ToString();
            textBox8.Text = dr["Phone"].ToString();            
            btnUpdate.Text = "Update";
            textBox2.ReadOnly = false;
            date1.Enabled = true;
            textBox6.Enabled = true;
            textBox7.Enabled = true;
            textBox8.Enabled = true;
            textBox6.ReadOnly = false;
            textBox7.ReadOnly = false;
            textBox8.ReadOnly = false;
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            textBox2.Enabled = true;
            textBox6.Enabled = true;
            textBox7.Enabled = true;
            textBox8.Enabled = true;
            if (textBox2.Text == "")
            {
                errorProvider1.SetError(textBox2, "You need to enter a valid Name");
                MessageBox.Show("Please fill in the empty fields. All fields are mandatory.", "Employee Master", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                errorProvider1.Dispose();
            }
            if (date1.Value == Convert.ToDateTime("1/1/1753") || date1.Value > Convert.ToDateTime(DateTime.Now))
            {
                errorProvider1.SetError(date1, "Please enter valid date");
                MessageBox.Show("Please enter valid date.", "Employee Master", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                errorProvider1.Dispose();
            }
            if (textBox6.Text == "")
            {
                errorProvider1.SetError(textBox6, "You need to enter a value (Your Gross Salary)");
                MessageBox.Show("Please fill in the empty fields. All fields are mandatory.", "Employee Master", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                errorProvider1.Dispose();
            }
                if (textBox7.Text == "")
                { 
                errorProvider1.SetError(textBox7, "You need to enter a value (Your Net Salary)");
                MessageBox.Show("Please fill in the empty fields. All fields are mandatory.", "Employee Master", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
                }
                else
                {
                errorProvider1.Dispose();
                }                
                if (comboBox1.SelectedIndex == 0)
                {
                    errorProvider1.SetError(comboBox1, "Please enter valid Employment Type");
                    MessageBox.Show("Please mention your EmploymentType - Permanent, Probation, Contractual or Trainee", "Employee Master", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    errorProvider1.Dispose();
                }
                if (comboBox2.SelectedIndex == 0)
                {
                    errorProvider1.SetError(comboBox2, "Please enter valid Department Type");
                    MessageBox.Show("Please mention your EmploymentType - Permanent, Probation, Contractual or Trainee", "Employee Master", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    errorProvider1.Dispose();
                }
                if (date1.Value < DateTime.Now)
                {
                    errorProvider1.SetError(date1, "Please enter valid Date");
                    MessageBox.Show("Please mention your DOJ", "Employee Master", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            EmpMaster updatedb = new EmpMaster();
            updatedb.EmpID = EmpID;
            updatedb.EmpName = textBox2.Text;
            updatedb.EmpType_ID = comboBox1.SelectedValue.ToString();
            updatedb.DepartmentID = comboBox2.SelectedValue.ToString();
            updatedb.DateofJoining = date1.Value;
            updatedb.GrossSalary = textBox6.Text;
            updatedb.NetSalary = textBox7.Text;
            updatedb.Phone = textBox8.Text;

            if (btnUpdate.Text == "Update")
            {                   
                if (updatedb.UpdateDB() < 0)
                {
                    MessageBox.Show(updatedb.errortext);
                    return;
                }
                run();
                foreach (DataGridViewRow dr in dataGridView1.Rows)
                {
                    if (dr.Cells["EmpID"].Value.ToString() == EmpID)
                    {
                        dr.Selected = true;
                    }
                }
                dataGridView1.CurrentRow.Selected = false;
                dataGridView1.CurrentCell.Selected = false;  
                MessageBox.Show("Record Updated");
            }
            else if (btnUpdate.Text == "Save")
            {
                if (updatedb.SaveDB() < 0)
                {
                    MessageBox.Show(updatedb.errortext);
                    return;
                }
                run();
                foreach (DataGridViewRow dr in dataGridView1.Rows)
                {
                    if (dr.Cells["EmpID"].Value.ToString() == EmpID)
                    {
                        dr.Selected = true;
                    }
                }
                dataGridView1.CurrentRow.Selected = false;
                dataGridView1.CurrentCell.Selected = false;  
                MessageBox.Show("Record Saved");
            }                     
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex == 0)
            {
                textBox3.Clear();
                textBox4.Clear();
            }
            else
            {
                textBox3.Text = comboBox1.SelectedValue.ToString();
            }
        }
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex == 0)
            {
                textBox3.Clear();
                textBox4.Clear();
            }
            else
            {
                textBox4.Text = comboBox2.SelectedValue.ToString();
            }
        }

        private void date1_DropDown(object sender, EventArgs e)
        {
            date1.Format = DateTimePickerFormat.Short;
            date1.Value = DateTime.Now;            
        }

        private void textBox8_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!((e.KeyChar > 47 && e.KeyChar <= 57) || (e.KeyChar == 8) || (e.KeyChar == 13) || (e.KeyChar == 9) || (e.KeyChar == 0) || (e.KeyChar == 127)))
            {
                errorProvider1.SetError(textBox8, "Please use 0-9 keys only. (Numpad)");
                MessageBox.Show("Please enter 0-9. Phone numbers don't have alphabets.", "Employee Master", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Handled = true;
            }
        }

        private void textBox6_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!((e.KeyChar > 47 && e.KeyChar <= 57) || (e.KeyChar == 8) || (e.KeyChar == 13) || (e.KeyChar == 9) || (e.KeyChar == 0) || (e.KeyChar == 127)))
            {
                errorProvider1.SetError(textBox6, "Please use 0-9 keys only. (Numpad)");
                MessageBox.Show("Please enter 0-9. Salary don't have alphabets.", "Employee Master", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Handled = true;
            }
        }

        private void textBox7_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!((e.KeyChar > 47 && e.KeyChar <= 57) || (e.KeyChar == 8) || (e.KeyChar == 13) || (e.KeyChar == 9) || (e.KeyChar == 0) || (e.KeyChar == 127)))
            {
                errorProvider1.SetError(textBox7, "Please use 0-9 keys only. (Numpad)");
                MessageBox.Show("Please enter 0-9. Salary don't have alphabets.", "Employee Master", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Handled = true;
            }
        }
    }
}


EmpMaster.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace EmployeeMaster
{    
   public class EmpMaster
    {
            DataSet ds;
            DataSet dsdept;
            DataSet dsemptype;            
            SqlDataAdapter da;            
            SqlCommand sc1;       
            public string EmpID
            {
                get;
                set;
            }
            public string EmpName
            {
                get;
                set;
            }
            public string EmpType_ID
            {
                get;
                set;
            }
            public string DepartmentID
            {
                get;
                set;
            }
            public string GrossSalary
            {
                get;
                set;
            }
            public string NetSalary
            {
                get;
                set;
            }
            public string Phone
            {
                get;
                set;
            }
            public DateTime DateofJoining
            {
                get;
                set;
            }
            public string errortext
            {
                get;
                set;
            }
        public DataTable Get()
            {                
                ds = new DataSet();                
                SqlDataAdapter da = new SqlDataAdapter();
                SqlConnection con = new SqlConnection();
                SqlCommand sc1 = new SqlCommand();
                sc1.CommandText = "Select EmployeeMaster.*, d.DepartmentName, z.EmploymentType from EmployeeMaster inner join dbo.Department d on d.DepartmentID = EmployeeMaster.DepartmentID inner join dbo.EmpType z on z.EmpType_ID = EmployeeMaster.EmpType_ID";
                da.SelectCommand = sc1;
                sc1.Connection = con;
                con.ConnectionString = ConfigurationSettings.AppSettings["con"];
                con.Open();
                da.Fill(ds);
                con.Close();            
                return ds.Tables[0];            
        }
        public DataTable GetEmpType()
        {
            SqlConnection con = new SqlConnection();
            sc1 = new SqlCommand();
            da = new SqlDataAdapter();
            sc1.CommandText = "Select * from EmpType order by EmploymentType";
            da.SelectCommand = sc1;
            sc1.Connection = con;
            con.ConnectionString = ConfigurationSettings.AppSettings["con"];
            con.Open();
            dsdept = new DataSet();
            da.Fill(dsdept);
            con.Close();
            return dsdept.Tables[0];
        }
        public DataTable GetDept()
        {
            SqlConnection con = new SqlConnection();
            sc1 = new SqlCommand();
            da = new SqlDataAdapter();
            sc1.CommandText = "Select * from Department order by DepartmentName";
            da.SelectCommand = sc1;
            sc1.Connection = con;
            con.ConnectionString = ConfigurationSettings.AppSettings["con"];
            con.Open();
            dsemptype = new DataSet();
            da.Fill(dsemptype);
            con.Close();
            return dsemptype.Tables[0];
        }
        public int UpdateDB()
        {
            int abc=0;
            SqlConnection con = new SqlConnection();
            try
            {

                SqlCommand sc1 = new SqlCommand();
                sc1.CommandText = "Update Employeemaster set phone ='" + Phone + "', empname ='" + EmpName + "', dateofjoining = '" + DateofJoining.ToShortDateString() + "', grosssalary = '" + GrossSalary + "', netsalary = '" + NetSalary + "', EmpType_ID = '" + EmpType_ID + "', DepartmentID = '" + DepartmentID + "' where EmpID = '" + EmpID + "'";
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = sc1;
                sc1.Connection = con;
                con.ConnectionString = ConfigurationSettings.AppSettings["con"];
                con.Open();
                abc = sc1.ExecuteNonQuery();
                if (abc < 0)
                {
                    return -1;
                }
               
            }
            catch (Exception ex)
            {
                errortext = ex.Message;
                return -1;
            }
            finally
            {
                con.Close();
            }
            return abc;
        }
        public int SaveDB()
        {
            int def = 0;
            SqlConnection con = new SqlConnection();
            try
            {
                SqlCommand sc1 = new SqlCommand();
                sc1.CommandText = "Insert into Employeemaster (empname, EmpType_ID, DepartmentID, grosssalary, netsalary, phone, dateofjoining) values ('" + EmpName + "', '" + EmpType_ID + "', '" + DepartmentID + "', '" + GrossSalary + "', '" + NetSalary + "', '" + Phone + "', '" + Convert.ToDateTime(DateofJoining).ToShortDateString() + "')";
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = sc1;
                sc1.Connection = con;
                con.ConnectionString = ConfigurationSettings.AppSettings["con"];
                con.Open();
                def = sc1.ExecuteNonQuery();
                if (def < 0)
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {
                errortext = ex.Message;
                return -1;
            }
            finally
            {
                con.Close();
            }
            return def;
        }
    }
}
Posted
Updated 4-Sep-11 18:08pm
v3
Comments
Sergey Alexandrovich Kryukov 4-Sep-11 23:54pm    
Well, this is called code dump. Think about it: who will be interested to read it not having your overview of it and explanation of your idea? What is "the same", why, what functionality you want to replace, why?
Use "improve question", maybe you can improve your chance to get some answer.
--SA
HarinderS 5-Sep-11 0:12am    
I want exactly same code, just i want to replace datatables and datasets with generic collection. I am just learning .Net and i have been given this task by my mentor. I am trying it from past 3 days on my own, but i failed. So i planned to ask experts of CodeProject about the same. I have been presented same question, so i asked it in the same way.

My mentor used the words "Good, you have done the assignment given by me (i.e. Employeemaster), but now let's make it more organised. You should use generic collections instead of datatables and datasets. So go ahead, learn about generic collections arraylists etc. and convert your code into an organised one."
Mehdi Gholam 5-Sep-11 0:52am    
Please don't ask for solutions to your homework assignments.
HarinderS 5-Sep-11 1:12am    
It's not homework, it is office work. I am not studying it. I am doing job in a gaming company, and apart from job, i am learning to program their ERP Software, in the same office. Our office has the option of learn alongwith earn. 1 hour study by office experts, and 8 hours work :)
GParkings 5-Sep-11 5:54am    
I think it would be best if you did the following:

- Do some research into generics (plenty of tutorials out there on the web) to make sure you understand what they are, why they are used, what limitations they have etc
- Talk to your mentor to clarify what exactly he wants you to do, it would appear you yourself are unsure of this and until YOU understand what you need to do we wont be able to either :)

Once thats done, have another go at it yourself and if there is a particular area on which you are having trouble submit a more concise question with regard to that. The large volume of code posted and the nature of the question being 'rewrite my code please' are off-putting to any would-be helpers.

Seems no one has answer to my question. Please tell me a way to delete my post at least.
 
Share this answer
 
v2
Here is the Pseudo code :
foreach row in datatable
   1. create a new employee object

   foreach column in row
      1. Using reflection set the property name with the column value

   2. add the created employee to generic collection
 
Share this answer
 
Comments
HarinderS 5-Sep-11 1:11am    
Didn't understand, can't you simply modify my code to what i want?
I am really a rookie. I don't even remember keywords. I keep forgetting them, and usually trouble my mentor just to know the keywords, lol :)

Moreover, you are using foreach row in datatable, which i have been instructed not to use. No datatables, no datasets... ???

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