Pass variables and perform actions between classes in C #

4

I am learning the C # language, also using the VisualStudio tool, and I can not pass a variable (BtnColor in the code) from one class to another, and then perform an action from the value of that variable. This is the form I try to create in VisualStudio:

The idea is that when you click on the first button, change the color of the button to red, and where it says "None Selected" (label1) the word "red" appears. This is the Code:

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 A___CambiarColorBotones
{
public partial class Form1 : Form
{
    protected string BtnColor;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        button1.BackColor = Color.Red;
        BtnColor = "red";
        CambiarColorBoton colorbtn = new CambiarColorBoton();
        colorbtn.CambiarColor(BtnColor);
    }
}
public class CambiarColorBoton:Form1
{
    string c;
    public void CambiarColor(string BtnColor)
    {
        c = BtnColor;
    }
    public void BtnColorCambiar()
    {
        if (c == "red")
        {
            label1 = "Rojo";
        }
    }

}

With this code, the error that comes up is: CS0122 - 'Form.label1' is not accessible due to its level of protection.

    
asked by Pablo Flores 25.08.2018 в 22:52
source

1 answer

3

To achieve what you are looking for, you have to pass label1 to the class you want to be able to modify it, for example ..

  public class CambiarColor
    {
        Label label;
        public CambiarColor(Label label)
        {
            this.label = label;
        }

        public void ModificarColor(string color)
        {
            label.Text = color;
        }
    }

Then to call the method ModificarColor(string color) only instances CambiarColor

CambiarColor a = new CambiarColor(label1);
a.ModificarColor("Rojo");

In this way, you will have the result you are looking for!

Greetings!

    
answered by 25.08.2018 / 23:45
source