Search code examples
c#winformswindows-forms-designerresx

How resx, designer and cs file pass values within the form?


In Windows form. There is a xml data in form.resx

<data name="$this.Text" xml:space="preserve">
  <value>Report</value>
</data>

So in form.designer.cs

public System.Windows.Forms.ListView report;
private void InitializeComponent()
{
this.report.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.report_ColumnClick);
}

In form.cs

private void report_ColumnClick(Object eventSender, ColumnClickEventArgs eventArgs)
        {
            if (this.Text != "Report")
            {
                //Some code
            }
        }

The question is how does the value in form.resx gets recognised in form.cs. How is this.text getting recognized in desginer and cs file


Solution

  • The relationship between Form.cs and Form.designer.cs is determined by the name of the class and the partial keyword.

    You can break classes into multiple parts or files as long as you give the class the same name and add the partial keyword in front of it, when compiling the compiler will see this as one big class.. eg.

    The Forms.cs file

    partial class Form
    {
     //contain all the implementation code for the form
     //all the code added by the programmer
    }
    

    The Form.designer.cs file

    partial class Form
    {
    // contains all the auto generated code
    // contains the InitializeComponent() method
    }
    

    When compiled the compiler will treat both of the files above as 1 class of Form.

    As for the .resx file, see this answer

    The .resx file also helps Visual studio in design time to keep track of values to display at design time.

    If you want to change the this.Text in code you can do so in the forms Load event. eg.

    private void Form1_Load(object sender, EventArgs e)
    {
        string oldText = this.Text; //oldText will be 'Report' or 'Form1'
        this.Text = "whatever you want it to be";
    }