Home > Net >  Where do I put an array so that It is accessible to windows form controls?
Where do I put an array so that It is accessible to windows form controls?

Time:12-04

I am working on a C# windows forms app trading card game collection manager

I have a Card class and I'm trying to create an array of Card objects to represent every card in the set. From there, I would like to be able to search and display the Card details on the forms text boxes, labels, picturebox etc.

I have tried putting the array in form1.cs and program.cs both inside and outside different classes. The only place the array seems to be in scope for the click event handler is when it is declared inside it.

Where can I initialize this array so it accessible throughout the whole program and in scope for the form event handlers? I'm very new to object oriented programming with windows forms

The Constructor for Card class takes one int parameter and initializes the "collector number"

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        const int NumberOfCardsInSet = 3;
        Card[] Set = new Card[NumberOfCardsInSet];
        for (int iii = 0; iii < NumberOfCardsInSet; iii  )
        { Set[iii] = new Card(iii   1); }
    }
}

The constructor for Card takes an int parameter just to set the set number. After this, the card objects are accessible and I can set their fields.. however down here:

private void button1_Click(object sender, EventArgs e)
{
    //test button
    DisplayCard(Set[0]);   //error: name "set" doesnt exist in current context
}


public void DisplayCard(Card selectedCard)
{
    myDCollectorNoTB.Text = selectedCard.CollectorNum.ToString();
    myDNameTB.Text = selectedCard.Name.ToString();
    myDRarityTB.Text = selectedCard.CardRarity.ToString();
    myDCostTB.Text = selectedCard.Cost.ToString();    
}

CodePudding user response:

The array needs to be declared within the scope of the class (as a member, just like the constructor or the button1_Click and DisplayCard methods). Basing this on your code:

public partial class Form1 : Form
{
    private const int NumberOfCardsInSet = 3;
    private Card[] Set = new Card[NumberOfCardsInSet];

    public Form1()
    {
        InitializeComponent();
        
        for (var i = 0; i < NumberOfCardsInSet;   i)
        { 
            Set[i] = new Card(i   1); 
        }
    }

    //your button1_Click and DisplayCard methods go here

}

CodePudding user response:

You can create a new class and name it something like "GlobalVars" and create a static variable inside of that class. You can then reference it from another class.

public static class GlobalVars
{
    public static object YourObject { get; set; }
}

Usage:

GlobalVars.YourObject = "hey";

  • Related