【问题标题】:How to display employee information in form2 by specifying emp id in form1?form1中指定emp id如何在form2中显示员工信息?
【发布时间】:2014-12-23 11:07:10
【问题描述】:

这是我设计的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();
        }
    } 
}

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

【问题讨论】:

  • 你的问题是什么>?
  • 当我在 form1 中输入 emp id 时,员工详细信息未显示在 form2 文本框中..
  • 使用两个表单都引用的模型类。通过构造函数或自定义属性在表单之间传递引用。

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


【解决方案1】:

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

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

【讨论】:

    【解决方案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 ..它显示 i 消息框无效的列名 ID
    【解决方案3】:

    您应该在此处将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 个名为 tbempid、tbempname、tbmbno 的文本框

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

    【讨论】:

    • 我无法访问表单 1 中的表单 2 控件……它显示保护级别错误……
    • 无法访问 f2.tbempid,f2.tbempname,f2.tbmbno
    【解决方案4】:

    以下是一个非常简单的示例,我将上面的建议汇总在一起。为简单起见,它不遵循最佳实践。下面重点关注的领域是 EmployeeModel class、Form1 和 Form2 源代码。

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

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

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

    在 Form2 的 Onload 事件中,label.Text 属性使用作为引用传递的 EmployeeModel 中包含的内容进行初始化。

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

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

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

    【讨论】:

      猜你喜欢
      • 2022-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多