How to display employee information in form2 by specifying emp id in form1?

2.9k Views Asked by At

This is my form1 which I designed. When I type emp id in form1's textbox and click on the search button it shows form2.

In this second form I need to carry all the details corresponding to emp id and should display details into corresponding textboxes.

I have created emp table in SQL Server...I would like to pull the employee details from the database based on emp id. This is my code:

form1:

private void btnsearch_Click(object sender, EventArgs e)
{
    Form2 f2 = new Form2(tbempid.Text);
    f2.Show();
    SqlConnection con = new SqlConnection("Data Source=RAJIM-PC;Initial Catalog=Practicing;User ID=sa;Password=RajiSha");

    try
    {
        con.Open();
        SqlCommand com = new SqlCommand("SELECT eid,emp_name,mobile_no FROM emp WHERE ID='" + tbempid.Text.Trim() + "'", con);
        com.CommandType = CommandType.Text;
        DataTable dtb = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(com);
        da.Fill(dtb);

        if (dtb.Rows.Count > 0)
        {
            Form2.txtempid.Text= dtb.Rows[0]["eid"].ToString();
            Form2.txtempname.Text = dtb.Rows[0]["emp_name"].ToString();
            Form2.txtmbno.Text= dtb.Rows[0]["mobile_no"].ToString();
        }

        FormCollection fc = System.Windows.Forms.Application.OpenForms;

        foreach (Form f in fc)
        {
            if (f.Name == "Form2")
            {
                f.Update();
            }
        }
    }
    catch (SqlException sql) 
    { 
        System.Windows.Forms.MessageBox.Show(sql.Message); 
    }
    finally
    {
        if (con.State == ConnectionState.Open)
        {
            con.Close();
            con.Dispose();
        }
    } 
}

form2:

public partial class Form2 : Form
{
    public static string txtempid;
    public static string txtempname;
    public static string txtmbno;

    public Form2(string strtxtbox)
    {
        InitializeComponent();
        tbempid.Text = strtxtbox;
    }
}
4

There are 4 best solutions below

0
On

The following is a very quick example that I've thrown together of what I suggested above. It does not follow best practice for purposes of simplicity. The areas to concentrate on below is the EmployeeModel class, Form1 and Form2 source.

The idea here is utilize the EmployeeModel class as a container that both forms have access to.

Form 1 acquires the employee information. (Keep in mind, the model class can contain any information you like. It does not have to be reserved for just properties. If you prefer, you can keep a reference to a dataset here.)

Form 2 has a reference to this EmployeeModel class. When the button click event is fired on form1, a new EmployeeModel class object is created and initialized with the relevant information that would be displayed in form2. It is then passed as an object reference using Form2's overloaded constructor.

On the Onload event of Form2, the label.Text properties are initialized with what is contained in the EmployeeModel that was passed as a reference.

This is a very basic implementation and in most real world applications where expandability and maintainability are also factors to consider, a MVP or MVVM WinForms architectural framework is typically used.

Form 1 designer:

namespace FormToFormExample
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(12, 12);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(260, 20);
            this.textBox1.TabIndex = 0;
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(197, 64);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 2;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 100);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.textBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Button button1;
    }
}

Form 2 designer:

namespace FormToFormExample
{
    partial class Form2
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(12, 9);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(35, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "label1";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(12, 34);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(35, 13);
            this.label2.TabIndex = 1;
            this.label2.Text = "label2";
            // 
            // Form2
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Name = "Form2";
            this.Text = "Form2";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
    }
}

Model class:

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

namespace FormToFormExample
{
    public class EmployeeModel
    {
        #region Properties
        private Guid _employeeID;
        public Guid EmployeeID
        {
            get { return this._employeeID; }
            set { this._employeeID = value; }
        }

        private string _name;
        public string Name
        {
            get { return this._name; }
            set { this._name = value; }
        } 
        #endregion

        #region Constructors
        public EmployeeModel()
        {
            this._employeeID = Guid.NewGuid();
        }

        public EmployeeModel(string name)
            : this()
        {
            this._name = name;
        } 
        #endregion
    }
}

Form 1 source:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FormToFormExample
{
    public partial class Form1 : Form
    {
        #region Constructors
        public Form1()
        {
            InitializeComponent();
            Initialize();
            BindComponents();
        } 
        #endregion

        #region Methods
        private void BindComponents()
        {
            this.button1.Click += button1_Click;
        }

        private void Initialize()
        {
            this.textBox1.Text = string.Empty;
        } 
        #endregion

        #region Events
        void button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2(new EmployeeModel(textBox1.Text));
            form2.ShowDialog();

            Initialize();
        } 
        #endregion
    }
}

Form 2 source:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FormToFormExample
{
    public partial class Form2 : Form
    {
        EmployeeModel _model;

        #region Constructors
        public Form2()
        {
            InitializeComponent();
            BindComponents();
        }

        public Form2(EmployeeModel model)
            : this()
        {
            this._model = model;
        } 
        #endregion

        #region Methods
        private void BindComponents()
        {
            this.Load += Form2_Load;
        }

        private void Initialize()
        {
            this.label1.Text = this._model.EmployeeID.ToString();
            this.label2.Text = this._model.Name;
        } 
        #endregion

        #region Events
        void Form2_Load(object sender, EventArgs e)
        {
            Initialize();
        }  
        #endregion
    }
}

Program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FormToFormExample
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}
0
On

Looks like your doing all the work for filling out Form2 in Form1, I would suggest moving the code into Form2 and calling it from the Form2's constructor. Not only will this make more sense, but means you will only hit your database once to get the results.

Alternatively, you could pass Form2 your data table from Form1 and use the values in Form2's constructor. Again, saving a second query going to the database.

1
On

You can take constructor of form 2 as shown below :-

 public Form2(string txtempid, string txtempname, string txtmbno)
        {
            InitializeComponent();
            txtempid.Text = txtempid;
            txtempname.Text = txtempname;
            txtmbno.Text = txtmbno;
        }

and in form 1 :-

var form2 = new Form2(dtb.Rows[0]["eid"].ToString(), dtb.Rows[0]["emp_name"].ToString(), dtb.Rows[0]["mobile_no"].ToString());  
2
On

You should change Form2 to f2 here:

Form2.txtempid.Text= dtb.Rows[0]["eid"].ToString();
Form2.txtempname.Text = dtb.Rows[0]["emp_name"].ToString();
Form2.txtmbno.Text= dtb.Rows[0]["mobile_no"].ToString();    

So it becomes:

f2.txtempid.Text= dtb.Rows[0]["eid"].ToString();
f2.txtempname.Text = dtb.Rows[0]["emp_name"].ToString();
f2.txtmbno.Text= dtb.Rows[0]["mobile_no"].ToString();  

Update 1

You are trying to assign those fields to the string variables. However, what you should do is to assign them to relevant textbox controls like this:

Assume you have 3 textboxes named tbempid, tbempname, tbmbno on Form2

f2.tbempid.Text= dtb.Rows[0]["eid"].ToString();
f2.tbempname.Text = dtb.Rows[0]["emp_name"].ToString();
f2.tbmbno.Text= dtb.Rows[0]["mobile_no"].ToString();  

Update 2

Due to the protection level, you need to add a function in Form2:

public void SetTextBoxes(string strempid, string strempname, string strmbno)
{
    tbempid.Text = strempid;
    tbempname.Text = strempname;
    tbmbno.Text = strmbno;
}

And change the 3 lines to:

f2.SetTextBoxes(dtb.Rows[0]["eid"].ToString(), dtb.Rows[0]["emp_name"].ToString(), dtb.Rows[0]["mobile_no"].ToString());