如何通过在form1中指定emp id来在form2中显示员工信息?

时间:2014-12-23 11:07:11

标签: c# winforms forms sql-server-2012 unique-values

这是我设计的form1。当我在form1的文本框中键入emp id并单击搜索按钮时,它会显示form2。

在第二种形式中,我需要携带与emp id对应的所有详细信息,并应将详细信息显示在相应的文本框中。

我在SQL Server中创建了emp表...我想基于emp id从数据库中提取员工详细信息。这是我的代码:

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();
        }
    } 
}

窗口2:

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 个答案:

答案 0 :(得分:0)

看起来你在Form1中填写Form2的所有工作,我建议将代码移动到Form2并从Form2的构造函数中调用它。这不仅会更有意义,而且意味着您只需访问一次数据库即可获得结果。

或者,您可以从Form1传递Form2数据表并使用Form2的构造函数中的值。再次,保存第二个查询到数据库。

答案 1 :(得分:0)

您可以使用如下所示的表单2的构造函数: -

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

并以表格1: -

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

答案 2 :(得分:0)

您应该在此处将Form2更改为f2

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();    

所以它变成了:

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();  

更新1

您正尝试将这些字段分配给字符串变量。但是,您应该将它们分配给相关的文本框控件,如下所示:

假设您在Form2上有3个名为tbempidtbempnametbmbno的文本框

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();  

更新2

由于保护级别,您需要在Form2

中添加一项功能
public void SetTextBoxes(string strempid, string strempname, string strmbno)
{
    tbempid.Text = strempid;
    tbempname.Text = strempname;
    tbmbno.Text = strmbno;
}

并将3行更改为:

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

答案 3 :(得分:0)

以下是一个非常快速的例子,我将上面提到的内容放在一起。出于简化的目的,它不遵循最佳实践。下面要关注的领域是 EmployeeModel Form1 Form2源

这里的想法是将EmployeeModel类用作两个表单都可以访问的容器。

表单1获取员工信息。 (请记住,模型类可以包含您喜欢的任何信息。不必仅为属性保留。如果您愿意,可以在此处保留对数据集的引用。)

表单2引用了此EmployeeModel类。当在form1上触发按钮单击事件时,将创建一个新的EmployeeModel类对象,并使用将在form2中显示的相关信息进行初始化。然后使用Form2的重载构造函数将其作为对象引用传递。

在Form2的Onload事件中,label.Text属性初始化为EmployeeModel中包含的作为参考传递的内容。

这是一个非常基本的实现,在大多数现实应用中,可扩展性和可维护性也是需要考虑的因素,通常使用MVPMVVM WinForms架构框架。

表单1设计师:

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;
    }
}

表单2设计师:

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;
    }
}

模特课程:

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
    }
}

表单1来源:

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
    }
}

表格2来源:

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
    }
}

<强>程序:

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());
        }
    }
}