4

How can I correctly replace hardcoded string for labels in Form1.Designers.cs?

Instead of:

        this.button1.Text = "TheButton";
        this.label1.Text = "TheLabel";

I want to write:

        this.button1.Text = Resources.ButtonText;
        this.label1.Text = Resources.LabelText;

After changing form in visual designer (add any component and save) VS code generator turns back label text to hardcoded string:

        this.button1.Text = Resources.ButtonText;
        this.label1.Text = "TheLabel";

Is anybody knows how to solve this issue?

Skiv
  • 43
  • 3

3 Answers3

3

Prevent Auto code change in Designer.cs for a specific line

using System;
using System.Windows.Forms;

namespace Test
{
    public partial class Form1 : Form
     {
       public Form1()
         {
           InitializeComponent();
           this.button1.Text = Resources.ButtonText;
         }
     }
}
Community
  • 1
  • 1
Danila Polevshchikov
  • 2,228
  • 2
  • 24
  • 35
  • 1
    This is not good solution for me. I would like to see label's text in designer and also I don't want to duplicate any code. For buttons replacing of hardcoded strings works perfect but for labels don't. – Skiv Nov 19 '13 at 06:45
  • Sad, but I didn't find better solution. – Skiv Nov 19 '13 at 11:55
2

The easiest would be to make your own Button/Label, where it takes its Text property from Resources:

class MyButton: Button
{
    // put here attributes to stop its serialization into code and displaying in the designer
    public new string Text
    {
        get {return base.Text;}
        set {base.Text = value;}
    }

    public MyButton() : base()
    {
        base.Text = Resources.ButtonText;
    }
}
Sinatr
  • 20,892
  • 15
  • 90
  • 319
0

Just found the solution to prevent the reversion of the reference in the designer.cs file.

Instead of

this.label1.Text = MyNamespace.Properties.Resources.gui_lable1_text;

make it

this.label1.Text = global::MyNamespace.Properties.Resources.gui_lable1_text;
4b0
  • 21,981
  • 30
  • 95
  • 142
justme
  • 1