c# - 反复使用Form Constructor刷新标签文字

标签 c# winforms refresh

我是 C# 的新手,我有一个小项目。我被困在某个地方了。我在这里解释了它(带有示例源代码):

我有一个表格申请。我要求用户从 2 个按钮中选择一个选项。有 2 个按钮(是和否)。我的代码是这样的:

public partial class Form1 : Form
{
   public int choice=0;
   public Form1()
   {
      if(choice == 0)
      {
         label.Text = "Please push one of these buttons :";
         // And there are buttons below this label
      }
      else if(choice == 1)
      {
         label.Text = "You just pushed YES button";
      }
      else if(choice == 2)
      {
         label.Text = "You just pushed NO button";
      }
   }

   private void buttonYes_Click(object sender, EventArgs e)
   {
       choice = 1;
       /*
          I have to use one of these here for redraw whole form
          this.Refresh();
          this.Invalidate();
       */
   }
   private void buttonNo_Click(object sender, EventArgs e)
   {
       choice = 2;
       /*
          I have to use one of these here for redraw whole form
          this.Refresh();
          this.Invalidate();
       */
   }
} 

如您所见,当用户单击"is"或“否”按钮之一时,应该重新执行整个构造函数。标签应该是“你刚刚按下是/否按钮”。

但是当我使用 this.Refresh() 时,当我点击按钮时没有任何反应。仍然标签是“请按这些按钮之一:”。

当我使用 this.Invalidate() 时,所有按钮都消失了,标签仍然是“请按这些按钮之一:”。

我该怎么办?

谢谢。

附言 我找到了 this question在问这个之前。但如您所见,接受的答案对我不起作用。

最佳答案

无效或刷新不会再次调用构造函数。创建表单时只调用一次构造函数,并且无效不会创建新表单。将更改内容的逻辑放在另一个方法中,并从构造函数和事件处理程序中调用它 - 但请注意后代调用实例方法或从构造函数访问变量并不是做这些事情的最好方法 - 但对于您在这里的目的是简单的解决方案。

public partial class Form1 : Form
{
   public int choice=0;
   public Form1()
   {
      UpdateForm();
   }
   private void UpdateForm(){
      if(choice == 0)
      {
         label.Text = "Please push one of these buttons :";
         // And there are buttons below this label
      }
      else if(choice == 1)
      {
         label.Text = "You just pushed YES button";
      }
      else if(choice == 2)
      {
         label.Text = "You just pushed NO button";
      }
   }
   private void buttonYes_Click(object sender, EventArgs e)
   {
       choice = 1;
       /*
          I have to use one of these here for redraw whole form
          this.Refresh();
          this.Invalidate();
       */
       UpdateForm();
   }
   private void buttonNo_Click(object sender, EventArgs e)
   {
       choice = 2;
       /*
          I have to use one of these here for redraw whole form
          this.Refresh();
          this.Invalidate();
       */
      UpdateForm();

   }
} 

关于c# - 反复使用Form Constructor刷新标签文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15820805/

相关文章:

c# - 以编程方式将单元格和行添加到 DataGridView

html - 在 Rails 中刷新后 CSS 未加载

c# - InkCanvas 加载/保存操作

c# - 排序字典时出错

c# - FontSize.PIXELS c# 等价物

javascript - 在不刷新页面的情况下重新加载图像

javascript - 如何设置mousemove更新速度?

c# - 如何在 C# 中返回 postgresql 函数的结果?控制台输出为空

c# - 了解一行中使用的 Task.Run + Wait() + async + await 的使用

c# - 在 C# Windows 窗体中通过 IE 浏览器传递 AD 身份验证凭据