D
D
Denis2021-01-24 10:37:19
C++ / C#
Denis, 2021-01-24 10:37:19

How to change title of WinForm c#?

I have 2 forms, when I clicked a button in the first form (Form2), the name of another form (Form1) was changed

Code in Form1

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace FormName
{
  public partial class MainForm : Form
  {
    public MainForm()
    {
      InitializeComponent();
      Form2 st = new Form2();
      st.Show();
    }
    public static void name(string name){
      this.Text = name;
    }
  }
}


Code in Form2

using System;
using System.Drawing;
using System.Windows.Forms;

namespace FormName
{
  public partial class Form2 : Form
  {
    public Form2()
    {
      InitializeComponent();
    }
    
    void Button1Click(object sender, EventArgs e)
    {
      if(textBox1.Text != null) MainForm.name(textBox1.Text);
    }
  }
}


If compiled, it throws an error - Keyword 'this' is not valid in a static property, static method, or static field initializer (CS0026)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-01-24
Folyush @AAGR

public static void name(string name){
      this.Text = name;
    }

You have a static method here.
Static methods cannot use this.
Use the normal method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question