【问题标题】:How can I make refresh a Textbox from another form? C#如何从另一个表单刷新文本框? C#
【发布时间】:2021-11-08 15:56:01
【问题描述】:

我正在尝试使用此代码从另一个表单更新文本框:

private void Button2_Click(object sender, EventArgs e)
{
    Variables.revenu += Variables.LAIR * 30;
    Cartel_Form.Textbox_Revenu.Text = Variables.revenu.ToString();
}

但我收到此错误:

非静态字段、方法或属性“Cartel.Form.Textbox_Revenu”需要对象引用

这是第一种形式的文本框的内容:

Textbox_Revenu.Text = Variables.revenu.ToString();

在同一个表单中,我可以刷新/修改文本框,但不能在其他表单中。文本框修饰符设置为 public。

【问题讨论】:

  • Cartel_Form 是另一个表单的实例还是一个类的名称?
  • 是表格的名字
  • 您可以使用delegates 来更新/访问无法访问的代码部分。
  • @DarshanFaldu 我如何在这里使用它?
  • 您需要将实例或Action<string> 传递给其他表单。您可以像这样在Cartel_Form 中创建一个方法:public void WriteToTextBox(string text)。在其中放置您的代码。然后将方法作为参数传递给另一个表单的构造函数

标签: c# forms winforms textbox


【解决方案1】:

这是一个使用事件的示例,其中子窗体包含事件,而主窗体侦听这些事件。两种形式都有一个 TextBox 和一个 NumericUpDown 控件。或者正如@jimi 提到的使用绑定。

主窗体

using System;
using System.Windows.Forms;

namespace PassingDataBetweenFormsSimple
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void ShowChildButton_Click(object sender, EventArgs e)
        {
            ChildForm childForm = new ChildForm();
            
            childForm.PassingData   += ChildFormOnPassingData;
            childForm.PassingNumber += ChildFormOnPassingNumber;

            try
            {
                childForm.ShowDialog();
            }
            finally
            {
                childForm.Dispose();
            }
            
        }

        private void ChildFormOnPassingNumber(int value)
        {
            numericUpDown1.Value = numericUpDown1.Value + value;
        }

        private void ChildFormOnPassingData(string text)
        {
            FirstNameTextBox.Text = string.IsNullOrWhiteSpace(text) ? 
                "(empty)" : 
                text;
        }
    }
}

子表单

using System;
using System.Windows.Forms;

namespace PassingDataBetweenFormsSimple
{
    public partial class ChildForm : Form
    {
        public delegate void OnPassingText(string text);
        public event OnPassingText PassingData;

        public delegate void OnPassingNumber(int value);
        public event OnPassingNumber PassingNumber;
        public ChildForm()
        {
            InitializeComponent();
        }

        private void PassDataButton_Click(object sender, EventArgs e)
        {
            PassingData?.Invoke(FirstNameTextBox.Text);
            PassingNumber?.Invoke((int)numericUpDown1.Value);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 2017-05-16
    • 2012-05-25
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多