繁体   English   中英

在 Windows 窗体中将一种形式的文本框值传递到另一种形式

[英]Passing Textbox Values one form to another form in Windows Forms

我正在尝试从用户那里获取用于绘制圆形(为此我使用半径输入)和矩形(Edge1 和 Edge2)输入的输入值。 我想在另一个表单上传递这些 textboxt 值来绘制它们。 如何将这些值移动到属性部分或任何解决方案中的另一种形式?

顺便说一下,表单在同一个项目中。

我定义了一个接口并实现了有关计算的过程。 我的代码在下面并且有效,感谢您的回复。

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

namespace Assignment2
{
    class CircleShape : Shape, IShape
    {
        public int radius;
        public CircleShape(int radius)
        {
            this.radius = radius;


        }
        public double CalculateArea()
        {
            return Math.PI * radius * radius;
        }

        public double CalculatePerimeter()
        {
            return 2 * Math.PI * radius;
        }
    }
}

一种方法是在你的第二个表单上有一个方法来返回任何需要的细节

using (DrawForm drawForm = new DrawForm ())
{
    drawForm.ShowDialog(); //will wait for the form to close before continuing
    var userResults = drawForm.GetResults(); //returns whatever you need the form to return
    return userResults;
}

仅当第二种形式是某种弹出形式时,上述逻辑才有效。 如果您希望两种形式都具有持久性,那就有点不同了。 您可能希望确保两个表单都可以相互访问。 当您创建 drawform 时,请务必保存对它的引用。 并在 drawform 的构造函数中添加一个参数以包含主窗体。

  DrawForm drawForm = new DrawForm(this);//now the forms can talk to each other

当用户点击“开始”时,在您的绘图表单中

 mainForm.TriggerFinishedDrawing(drawingObject);

有几种方法可以实现这种行为,您只需要确定哪种流程在您的用例中最有意义

将数据从一个表单传递到另一个表单的一种简单方法是您可以使用Application.OpenForms Property

首先,定义一个TextBox property来访问 Form1 中的 TextBox 实例。

// Form1.cs
public TextBox TB
{
    get { return textBox1; }
    set { textBox1 = value; }
}

然后调用Application.OpenForms来获取 Form1 实例。

// Form2.cs
Form1 fr = (Form1)Application.OpenForms["Form1"];
if (fr != null)
{
    Form1 f1 = (Form1)fr;
    // get text form Form1.textbox1
    MessageBox.Show(f1.TB.Text);
}

如果通过单击 Form1 中的按钮打开 Form2 并在 Form2 显示时传递值,则可以通过constructor实现。

// Form1.cs
private void btnOpenForm2_Click(object sender, EventArgs e)
{
    Form2 f2 = new Form2(textBox1.Text);
    f2.Show();
}

// From2.cs
string textformForm1;
public Form2(string str)
{
    InitializeComponent();
    textformForm1 = str;
}

private void btnShowText_Click(object sender, EventArgs e)
{
    MessageBox.Show(textformForm1);
}

同样,您也可以使用公共属性。

// Form1.cs
private void btnOpenForm2_Click(object sender, EventArgs e)
{
    Form2 f2 = new Form2();
    f2.TextformForm1 = textBox1.Text;
    f2.Show();
}

// Form2.cs
public string TextformForm1 { get; set; }

private void btnShowText_Click(object sender, EventArgs e)
{
    MessageBox.Show(TextformForm1);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM