如何在C#表单中修改标签文本

时间:2019-07-31 22:45:41

标签: c# winforms label

(我对C#还是很陌生)正在创建一个表单应用程序,目的是从Web API获取字符串,然后将该文本放在标签上。我已经成功地从Web上获取了数据,但是当我尝试更新标签时,我没有运气。 我已经调试,发现我的类 Is 中的方法正在执行,但是没有设置标签的文本。如下所示,我尝试使用this.resultLabel.text = str;。这是课程:

Program.cs(不是CS文件格式)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using System.Net;
using System.IO;
namespace WebsiteAPITest
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

        }

    }
    class PostManager
    {
        public void setupClient()
        {


            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format("https://yakovliam.com/phpApi/csTest.php"));

            WebReq.Method = "GET";

            HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

            string respStr;
            using (Stream stream = WebResp.GetResponseStream())   //modified from your code since the using statement disposes the stream automatically when done
            {
                StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
                respStr = reader.ReadToEnd();
            }

            MessageBox.Show(respStr);
            Form1 form = new Form1();
            form.SetResultLabel(respStr);

        }


    }

}

实际表单类(Form1.cs)

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;

namespace WebsiteAPITest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void GetButton_Click(object sender, EventArgs e)
        {
            PostManager postManager = new PostManager();
            postManager.setupClient();
        }
        public void SetResultLabel(string str)
        {
            this.resultLabel.Text = str;
            this.resultLabel.Refresh();
        }
    }

标签名称证明:Img of label

1 个答案:

答案 0 :(得分:1)

setupClient内部,您致电Form1 form = new Form1();会创建另一个Form1,您将永远不会显示它,然后在从未显示的第二个表单中调用SetResultLabel(respStr),然后离开方法并丢弃它。

如果您要致电呼叫表格的SetResultLabel,则必须将呼叫表格传递给setupClient

public void setupClient(Form1 callingForm)
{
    ...
    callingForm.SetResultLabel(respStr);

然后在您的Form1中:

postManager.setupClient(this);

将表格传递给其他方法非常危险;更好的设计是让其他方法将数据返回到表单:

public string setupClient()
{
    ...
    return respStr;
}

Form1内:

SetResultLabel(postManager.setupClient());