【问题标题】:C# Windows Form Text is not updatingC# Windows 窗体文本未更新
【发布时间】:2022-08-23 17:06:49
【问题描述】:

我是使用 Windows 窗体编程的新手。 我创建了一个服务器和一个客户端,其中服务器以字节数组的形式向客户端/客户端发送数据,客户端正在对其进行解码并使用它接收到的信息更新他的文本框。

我的问题:它不会更新实际表格。

通过单击表单 (ClientForm) 上的按钮,调用另一个类的方法,该方法将其连接到服务器并接收数据。 然后将此数据解码(见下文)并通过我要更新文本框的字符串数组发送到表单类。

这是一些可视化它的代码:

客户表格:

public partial class ClientForm : Form
    {
        public ClientForm()
        {
            InitializeComponent();
            
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            // this button connects the client to the server
            
        }

        // this methode is called outside of this class, see below
        public void SendDecodedData(List<String> data)
        {
          textbox1.Text = data[0];
          textbox2.Text = data[1];
          textbox3.Text = data[2];
        }
    }


通过在其中一些更改处停止代码,我可以看到 textbox.Text 实际上已更新,但是它没有显示在表单上。

这就是我解码的方式(例如):

internal class Decode
    {
        public static void DecodeReceivedData(byte[] data)
        {
            ClientForm form = new ClientForm();

            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

            int telegramID = BitConverter.ToInt32(data, 0);
            byte[] verByte = new byte[4];
            Array.Copy(data, 18, verByte, 0, 4);
            string version = enc.GetString(verByte);
            int telegramLength = BitConverter.ToInt32(data, 8);
            
                List<String> decodedData = new List<String>()
                {
                    telegramID.ToString(), version, telegramLength.ToString(), 
                };
                

                form.SendDecodedData(decodedData);

            }
       }

如果我在表单中调用方法发送编码数据,例如而不是连接:

private void btnConnect_Click(object sender, EventArgs e)
        {
            List<String> list = new List<String>()
                    { \"text1\", \"text2\", \"text3\", \"text4\"};
            SendDecodedData(list);
            
        }

它确实有效。有一些我不知道也无法在互联网上找到的规则,它说明了如何更改表单类之外的文本框。

有谁能够帮我?

如果问题没有明确说明或我忘记了重要信息,请发表评论并告诉我!我在这里问的不多。

该问题类似于下面链接的问题,但不幸的是没有答案。

C# TextBox Control Not Updating With New Text

  • 链接的问题实际上有一个很多的相关答案。更新可见 TextBox\ 的 Text 属性有效。如果不是,数百万开发人员会在 20 年前注意到这一点。您发布的代码从未显示它创建的形式,这意味着您看到的任何形式都是不同的形式。

标签: c# winforms


【解决方案1】:

您正在DecodeReceivedData 中创建一个新的表单实例来设置文本框,但这与向用户显示的表单实例不同,这就是您所做的更改不可见的原因。

无需在DecodeReceivedData 中创建新的ClientForm,您只需将List&lt;string&gt; 传回并让表单本身更新文本框。

【讨论】:

  • 一个更简洁的选择是返回 List&lt;string&gt; 并让表单自行更新。 DecodeReceivedData 不需要了解表单
  • 好点子。相应地更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 2013-11-01
  • 1970-01-01
  • 2012-01-23
  • 2018-10-23
相关资源
最近更新 更多