程序不会获取文本或设置文本

时间:2016-01-28 18:08:17

标签: c# winforms

在我的C#windows窗体项目中,我的程序无法从文本框中获取文本,也无法设置文本框。我可以注册按钮点击,所以程序GUI线程似乎没问题。

private void sendButton_Click(object sender, EventArgs e)
{
    Console.WriteLine("I am being pressed");
    textBox2.Text = "Test";
    this.Refresh();
}

正如您在按下按钮时从代码中看到的那样,输出面板显示“我正被按下”。但是,文本框不会在视觉上更新并说“测试”。

我有无法设置或获取文字的原因。我试过附加文本,但这不是我的意图。

我的猜测是,表格可能并未集中,因为我已经改变了正在显示的形式。下面的代码来自第一个表单类。 lobby是我展示的新Form

if (correct)
{
    lobby lob = new lobby(client, this);
    this.Hide(); // this is the first form the user sees, I have hidden it. If I close this form then the application exits.
    lob.Show(); // this is the form that I show after the user logs in with right credentials. Textbox.text = "test" does not work on this for some reason.                
}

在第一个表单窗口中,我可以使用Text方法并检索/设置值。

但我不能以第二种形式做同样的事。

--------编辑------- 这是第二种形式的GUI构建器。 GUI Buider 您可以看到名称字段名为“TextBox2”。

lobby.cs文件

using System.Net.Sockets;
using System.Windows.Forms;

namespace ClientMMO
{
    public partial class lobby : Form
    {
        static int counter;
        private Socket client;
        private Form1 form1;

        public lobby()
        {
            InitializeComponent();
        }

        public lobby(Socket client)
        {
            InitializeComponent();
            this.client = client;   

        }

        public lobby(Socket client, Form1 form1) : this(client)
        {
            InitializeComponent();
            this.form1 = form1;

            textBox2.Text = "Test";

        }

    }
}

lobby.Designer.cs

namespace ClientMMO
{
    partial class lobby
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // textBox2
            // 
            this.textBox2.Location = new System.Drawing.Point(107, 90);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(251, 20);
            this.textBox2.TabIndex = 0;
            // 
            // lobby
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(511, 413);
            this.Controls.Add(this.textBox2);
            this.Name = "lobby";
            this.Text = "lobby";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox textBox2;
    }
}

这是用户看到的第一种形式。这里的一切都正常,应该如此。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
using System.Xml.Serialization;

namespace ClientMMO
{
    public partial class Form1 : Form
    {
        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        User test;
        public Form1()
        {
            InitializeComponent();
            ConnectToServer();
        }

        private void ConnectToServer()
        {
            IPAddress ipAddress = IPAddress.Loopback;
            IPEndPoint ep = new IPEndPoint(ipAddress, 1234);
            client.Connect(ep);
            Console.WriteLine("connnected");

        }

        private void button1_Click(object sender, EventArgs e)
        {
            test = new User();
            test.UserName = textBox1.Text;
            test.Password = textBox2.Text;
            client.Send(ClassToByteArray(test));
            byte[] data = new byte[1024];
            client.Receive(data);
            string returndata = System.Text.Encoding.ASCII.GetString(data);
            label1.Text = returndata;
            //Console.WriteLine(returndata);
            string b = "Logged in";

            int result = 0;
            string str1 = "Logged in";


            result = string.Compare(str1, returndata);
            if (result == 0)
            {
                button1.Visible = false;
                byte[] shit = new byte[1024];
                client.Receive(shit);
                Console.WriteLine(shit.ToString());
                string sfs = System.Text.Encoding.ASCII.GetString(shit);
                label1.Text = String.Empty;
                label1.Text = sfs;

                int port = Int32.Parse(sfs);
                client.Close();
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ipAddresse = IPAddress.Loopback;
                IPEndPoint epe = new IPEndPoint(ipAddresse, port);
                client.Connect(epe);
                Console.WriteLine("connected to another server");


                /*------------------------------------This is where I open up my new window --------------------*/


                lobby lob = new lobby(client, this);
                this.Hide(); // this is the first form the user sees, I have hidden it. If I close this form then the application exits.
                lob.Show(); // this is the form that I show after the user logs in with right credentials. Textbox.text = "test" does not work on this for some reason.

            }
            else
            {
                label1.Text = "failed";
            }


        }

        private byte[] ClassToByteArray(Object objClass)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                XmlSerializer xmlS = new XmlSerializer(typeof(User));
                XmlTextWriter xmlTW = new XmlTextWriter(ms, Encoding.UTF8);

                xmlS.Serialize(xmlTW, objClass);
                ms = (MemoryStream)xmlTW.BaseStream;

                return ms.ToArray();
            }
            catch (Exception)
            {
                throw;
            }
        }

        private Object ByteArrayToClass(byte[] buffer)
        {
            try
            {
                XmlSerializer xmlS = new XmlSerializer(typeof(User));
                MemoryStream ms = new MemoryStream(buffer);
                XmlTextWriter xmlTW = new XmlTextWriter(ms, Encoding.UTF8);

                return xmlS.Deserialize(ms);
            }
            catch (Exception)
            {
                throw;
            }
        }



    }


}

3 个答案:

答案 0 :(得分:0)

假设您正确地开始使用主表单,那么您正在做的事情应该有效。您可以在设置text属性后尝试放置Application.DoEvents()。确保你没有等待信号量或其他东西。

您是否将lob存储为类变量而不是局部变量?

答案 1 :(得分:0)

对此没有答案,我可以用&#34;修复&#34;错误(如果有的话)。

但解决方案是创建一个新的Windows表单文件并重新开始。

答案 2 :(得分:0)

我不认为这是一个错误。我想你正试图从另一种形式访问私人对象。 在lobby.cs中编写一个新方法,将textBox1的文本设置为:

public void SetText(string text){
 textBox2.Text = text;
}

然后当你隐藏主表格时:

lobby lob = new lobby(client, this);
this.Hide();
lob.SetText("Test");  
lob.Show();