C# 从另一个类引用文本框

标签 c# textbox reference

C# 的新手所以要好...

我正在尝试使用以下代码将一些文本发送到表单文本框:

SettingsForm.cs

 namespace BluMote
 {
      public partial class SettingsForm : Form
      {
           public void send2Display(string whatWasSent)
           {
               this.rtbDisplay.Text = whatWasSent;
           }

           private void cmdOpen_Click(object sender, EventArgs e)
           {
               commToy.Parity = "None";
               commToy.StopBits = "One";
               commToy.DataBits = "8";
               commToy.BaudRate = "115000";
               commToy.PortName = "COM4";
               commToy.OpenPort();
           }
      .........
      }
 }

我正在(尝试)像这样从另一个类调用它:

namespace PCComm
{
    class CommunicationManager
    {
    #region OpenPort
    public bool OpenPort()
    {
        try
        {
            if (comPort.IsOpen == true) comPort.Close();
            comPort.BaudRate = int.Parse(_baudRate);
            comPort.DataBits = int.Parse(_dataBits);
            comPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), _stopBits);
            comPort.Parity = (Parity)Enum.Parse(typeof(Parity), _parity);
            comPort.PortName = _portName;
            comPort.Open();
            PCComm.frmMain form = new PCComm.frmMain();
            form.send2Display("test");
            return true;
        }
        catch (Exception ex)
        {
            DisplayData(MessageType.Error, ex.Message);
            return false;
        }
    }
    #endregion
}
}

并且“test”不显示在文本框字段中

但是如您所见,它不起作用...我错过了什么?

大卫

最佳答案

send2Display是方法,需要带参数调用,不能赋值给它。

BluMote.SettingsForm form = new BluMote.SettingsForm();
form.send2Display("test");

编辑:

如果您从 SettingsForm 类内部调用该方法,则无需创建新实例。尝试:

this.send2Display("test");

根据更新的问题进行编辑:

问题是您在 OpenPort() 中创建的表单不是显示在屏幕上的表单,因此对文本框的任何更新都不会显示在屏幕上。这里有一些快速而肮脏的方法来解决这个问题:

  • 将对文本框的引用传递到您的方法中。我不推荐这种方法,因为您最终会在模型中看到 View 依赖项。
  • 从 OpenPort() 返回一个字符串并将返回值传递给 sendToDisplay。
  • 在 CommunicationManager 中定义一个字符串类型的属性 LastMessage 并在 OpenPort() 中分配给它。然后在 SettingsForm 中读取它并将其值传递给 sendToDisplay。

关于C# 从另一个类引用文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6977540/

相关文章:

c# - 对文本框对象列表进行排序

java - 使用 Java 中的引用来创建副作用

excel - VBA将2个用户表单文本框中的值合并到第三个文本框中

c# - 使用 winmm 的 mp3 播放器,事件 mp3 结束

c# - 如何确保dll的存在

c# - 为什么 Stream.Write 不采用 UInt?

javascript - 向文本框添加永久前缀

C++为具有引用成员变量的类创建复制构造函数

c++ - 使用 decltype 理解类型推导

c# - 通过WebRequest C#将JSON字符串发布到ElasticSearch