如何将一个 windows 窗体页面中的所有用户输入和标签复制到另一个以表格样式显示的 windows 窗体页面?

问题描述

我正在使用 Windows 窗体应用程序 C#,并创建了一个带有标签和文本框以及复选框的窗体(清单)。在我的第二个表单 (test_results) 页面中,我创建了一个 tablelayoutpanel,其中包含第一个表单中的所有数据。我的第一个表单上的“提交”按钮有。我选择 tablelayoutpanel 是因为我复制的表单是一个 excel 表单,用户希望它看起来与 excel 中的完全一样。结果在我运行时显示出来,但正如您所看到的,这仅适用于 tablelayoutpanel 上的 3 个文本框,实际上大约有 25 个。我只是不确定这是最佳实践和最简单的方法。请参阅下面的两种形式的代码

表格 1

namespace IppInspectSheet
{
    public partial class checkList : Form
    {
        public checkList()
        {
            InitializeComponent();
        }

        private void checkList_Load(object sender,EventArgs e)
        {

        }

        private void nextButton_Click(object sender,EventArgs e)
        {
            SetValueForText1 = textBox1.Text;
            SetValueForText2 = textBox2.Text;
            SetValueForText3 = textBox3.Text;
            test_results_Label t = new test_results_Label();
            t.Show();
            //Form3 f = new Form3();
            //f.Show();


        }

        private void groupBox1_Enter(object sender,EventArgs e)
        {

        }

        public static string SetValueForText1 = "";
        public static string SetValueForText2 = "";
        public static string SetValueForText3 = "";

表格 2

namespace IppInspectSheet
{
    public partial class test_results_Label : Form
    {
        public test_results_Label()
        {
            InitializeComponent();
        }

        private void test_results_Label_Load(object sender,EventArgs e)
        {
            textBox1.Text = checkList.SetValueForText1;
            textBox2.Text = checkList.SetValueForText2;
            textBox3.Text = checkList.SetValueForText3;
        }
    }
}

解决方法

Winforms 是 UI 框架,负责显示给定的数据结构并向该数据结构提供用户输入值。

您可以创建一个类型来表示您在 Form1 中的数据

public class MyData
{
    public string One { get; set; }
    public string Two { get; set; }
}

然后在 Form1 中“绑定”这些数据到表单控件。 Data Binding and Windows Forms

public class Form1
{
    private readonly MyData c;
    public Form1()
    {
        InitializeComponent();

        _data = new MyData();

        textbox1.Bindings.Add("Text",data,nameof(data.One),true,DataSourceUpdateMode .OnPropertyChanged);
        textbox2.Bindings.Add("Text",nameof(data.Two),DataSourceUpdateMode .OnPropertyChanged);
    }

    private void nextButton_Click(object sender,EventArgs e)
    {
        var form2 = new Form2(_data);
        form2.Show();
    }
}

在Form2的构造函数中添加参数,这样我们就可以向它传递数据了。

public class Form2
{
    private readonly MyData _data;
    public Form2(MyData data)
    {
        InitializeComponent();

        _data = data;

        label1.Bindings.Add("Text",nameof(data.One));
        label1.Bindings.Add("Text",nameof(data.Two));
    }
}