Home > other >  how to access array from one class to another class in C# winforms?
how to access array from one class to another class in C# winforms?

Time:07-29

I want to access array from one class to another class because my end-user enter the name list on one class. That list store into array in the same class. Then that name list access from another class. I'm not getting any errors in compile time. only I'm getting a run time error. I'm literally sorry to all coz I'm absolutely noob :(

public partial class custom : Form //class one which is end user enter the name list
{
    public string PresentValue;
    public string NormalValue;
    public string[] PValue = new string[50];//public array
    public string[] NValue = new string[50];//public array
}

public static int PresentArray = 0;// this line is used to increament the array index

private void cstmsvbtn_Click(object sender, EventArgs e)//this line enter the user namelist
{
        PresentValue = cstmtst1.Text   "_PV";//concatinate '_PV'
        NormalValue = cstmtst1.Text   "_NV";//concatinate '_NV'
        PValue[PresentArray] = PresentValue;
        NValue[PresentArray] = NormalValue;
        PresentArray  ;
}

public partial class print : Form//class two which is end user want to access that name list
{
 custom customarray = new custom();//im instatiate the custom cass object

 private void button1_Click(object sender, EventArgs e)//when i press this button message box show an empty white box only
    {
        MessageBox.Show(CustomArray.PValue[0],CustomArray.NValue[0]);
    }
}

CodePudding user response:

This is a common requirement and there are many ways to achieve this outcome (some of which might be considered "hacky"). Things I don't recommend:

  • Changing visibility to public for data fields that should be private
  • Creating tight dependencies of one form to the implementation details of another.
  • Creating "global" variables using the static keyword.

Since you claim to be a "noob" I'd like to suggest learning about the MainForm


PrintForm

The PrintForm requires the NValue and PValue arrays to do its printing. By declaring an event named ArrayRequest we give it the ability to request these arrays. Importantly, this class doesn't need to have any knowledge of where this information might be coming from.

public partial class PrintForm : Form
{
    public PrintForm() => InitializeComponent();

This is how the class can initiate the request

    public event ArrayRequestEventHandler ArrayRequest;
    protected virtual void OnArrayRequest(ArrayRequestEventArgs e)
    {
        ArrayRequest?.Invoke(this, e);
    }

When the button is clicked, try and get the information by callingOnArrayRequest

    private void buttonShowArray_Click(object sender, EventArgs e)
    {
        ArrayRequestEventArgs req = new ArrayRequestEventArgs();
        OnArrayRequest(req);
        if(req.Count == 0)
        {
            MessageBox.Show("Invalid Request");
        }
        else
        {
            String[] allValues =
                Enumerable.Range(0, req.Count)
                .Select(index => $"{req.NValue[index]} | {req.PValue[index]}")
                .ToArray();
            MessageBox.Show(
                text: string.Join(Environment.NewLine, allValues),
                caption: "All Values"
            );
        }
    }
}
// Defined outside the PrintForm class
public delegate void ArrayRequestEventHandler(Object sender, ArrayRequestEventArgs e);
public class ArrayRequestEventArgs : EventArgs
{
    public int Count { get; set; }
    public string[] PValue { get; set; }
    public string[] NValue { get; set; }
}

CustomForm

The CustomForm as shown in your post is the class that contains the arrays.

public partial class CustomForm : Form
{
    public CustomForm()
    {
        InitializeComponent();
    }

We give this class the ability to fulfill a request for the arrays.

    internal void ArraysRequested(object sender, ArrayRequestEventArgs e)
    {
        e.Count = _presentArray;
        e.NValue = _nValue;
        e.PValue = _pValue;
    }

The data held in this class should be private.

    // These should all be private
    // See naming conventions: https://stackoverflow.com/a/17937309/5438626
    // Set up visual studio to do this automatically: https://ardalis.com/configure-visual-studio-to-name-private-fields-with-underscore/
    private string _normalValue;
    private string _presentValue;
    private int _presentArray = 0;
    private string[] _pValue = new string[50];//public array
    private string[] _nValue = new string[50];//public array

    private void cstmsvbtn_Click(object sender, EventArgs e)
    {
        _presentValue = $"{cstmtst1.Text}_PV"; //concatinate '_PV'
        _normalValue = $"{cstmtst1.Text}_NV"; //concatinate '_NV'
        // Make sure index doesn't exceed the size of the array
        if ((_presentArray < _pValue.Length) && (_presentArray < _nValue.Length))
        {
            _pValue[_presentArray] = _presentValue;
            _nValue[_presentArray] = _normalValue;
            _presentArray  ;
        }
        else MessageBox.Show("Array is Full");
        Text = $"Custom: Count={_presentArray}";
        cstmtst1.Text = $"Hello {_presentArray   1}";
    }
}

MainForm

It is the MainForm class that oversees the operations and "knows" how the forms should interact. The constuctor method is where the connection is made between the event fired by PrintForm and the fulfillment by the CustomForm.

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
        // THIS IS THE "GLUE"
        _printForm.ArrayRequest  = _customForm.ArraysRequested;
    }
    private CustomForm _customForm = new CustomForm();
    private PrintForm _printForm = new PrintForm();

    // In MainForm.Designer.cs
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (components != null)
            {
                components.Dispose();
            }
            _customForm.Dispose();
            _printForm.Dispose();
        }
        base.Dispose(disposing);
    }
    private void buttonShowCustom_Click(object sender, EventArgs e)
    {
        _customForm.ShowDialog(owner: this);
    }
    private void buttonShowPrint_Click(object sender, EventArgs e)
    {
        _printForm.ShowDialog(owner: this);
    }
}

custom and print forms view


You will need to adapt this to your specific requirements but hopefully this will give you some basics to go on.

  • Related