Home > database >  Is there any way to make the input global?
Is there any way to make the input global?

Time:10-25

I want to use textBox1.Text in a different class not just in the main where the text boxes are defined so to say. Is there any way to make it global? Because it only allows me to use it in the main thing, not in the seperate class that I have to make in my task.

I need to store the text from the textBox in a List that is in a different class so the user can't add the same name twice so I need to remember what was typed in in the first input.

This is the class where I created a List and where I want to store those inputs:

internal class Clanovi
{
    public static List<Clan> Dodaj()
    {
        List<Clan> clanovi = new List<Clan>();
        clanovi.Add(new Clan() { KorIme = textBox1.Text, Lozinka = textBox2.Text });
        return clanovi;
    }
}
class Clan
{                                          
    public string KorIme { get; set; }
    public string Lozinka { get; set; }
}

This is WinForm btw.

CodePudding user response:

i suggest to:

  1. change the modifiers property in the properties of the textbox to public.

  2. write this code in the other class : Form_name/class_name

    myTextbox = new form_name/class_name();                       
    

    ex: Form1 myTextbox = new Form1();

  3. now u can use in any other class/form: mytextbox.Textbox.text.

    internal class Clanovi
    {
       Clan myTextbox = new Clan();
    
       public static List<Clan> Dodaj()
       {
         List<Clan> clanovi = new List<Clan>();
         clanovi.Add(new Clan() { KorIme = myTextbox.textBox1.Text, Lozinka = textBox2.Text });
         return clanovi;
       }
    }
    

CodePudding user response:

Your variable names are in another language so it is hard to understand but I think you want this

internal class Clanovi
{
    public static List<Clan> Dodaj()
    {
        Global.clanovi.Add(new Clan() { KorIme = textBox1.Text, Lozinka = textBox2.Text });
        // you don't need to return this since it is already global
        return clanovi;
    }
}

public static class Global
{
    public static List<Clan> clanovi = new List<Clan>();
}

public static class Clan
{                                          
    public static string KorIme { get; set; }
    public static string Lozinka { get; set; }
}

Whenever you want to access your global variables, you use the Global class with the static items in it.

  • Related