Home > Enterprise >  Populate list in form from a table (Entity Framework) then use in other places in the form code
Populate list in form from a table (Entity Framework) then use in other places in the form code

Time:07-16

New C# and Entity Framework user. I want to put the results of a table into a C# list. I want to reference this list in multiple form events. I will cycle through the list from beginning to end throughout the life of the form.

Currently, I have this code (snippet):

public partial class FrmMain : Form
{
    private readonly admEntities _admEntities = new admEntities();
    
    public FrmMain()
    {
        InitializeComponent();
    }

    private void frmMain_Load(object sender, EventArgs e)
    {
        var exhibitor = _admEntities.Exhibitors.ToList();

        // Put the first value in a text box - this works
        txtCurrentSaleOrder.Text = exhibitor.First().SaleOrder.ToString();
    }
}

I was hoping to use the exhibitor variable elsewhere on other events. However, I am unable to reference it.

I have not been successful in my searching and coding attempts to resolve this problem so far. Any pointer in the right direction would be appreciated.

One thing I tried was to put this code in a class above FrmMain(). That also failed. Probably due to not fully understanding classes yet.

CodePudding user response:

You should make exhibitor a field, which is a fancy way of saying declare it outside of a method, inside of your class. Here is an example where exhibitor can be accessed from anywhere else in the class.

public partial class FrmMain : Form
{
    private readonly admEntities _admEntities = new admEntities();
    
    //It's unclear what exhibitor is in your question, so I'm using generic code that will allow it to work regardless.
    private Type exhibitorType = typeof(admEntities.Exhibitors);
    private List<exhibitorType> exhibitor = new List<exhibitorType>();
    
    public FrmMain()
    {
        InitializeComponent();
    }

    private void frmMain_Load(object sender, EventArgs e)
    {
        //Can reference here
        exhibitor = _admEntities.Exhibitors.ToList();
        
        txtCurrentSaleOrder.Text = exhibitor.First().SaleOrder.ToString();
    }

    private void AnotherMethod()
    {
        //Can reference exhibitor here too.
    }
}
  • Related