none
Load Form1 And Initialize Components On UserControl Form On Start Using EF RRS feed

  • Question

  • Hello Guys,

    Please, I am trying to initialize components (like textbox) on a userControl Object. But the form that gets opened first is not the userControl, but another(mainPage form).

    An example is, once my MainPage form gets loaded, I have some textbox on the userControl object which I need populate from my database when starting the application.

    So, the idea is that, once the application starts, it should fetch data from the db and populate the textbox on the userControl.

    I have tried using a static field from the control. But again, on start, the UserControl does not get fired up.

    So, far, this is what I have on UserControl class

    public static MyControl fromMyControl;
    public MyControl()
           {
               InitializeComponent();
           }
    
    private void MyControl_Load(object sender, EventArgs e)
            {
                fromMyControl = this;
            }
    
    
    private List<items> GetItems()
            {
                using (Model db= new Model())
                {
                    return db.items.ToList();               
                }
                
            }
    

    And here is the MainPage Class

    void InitControls()
            {
                var result = GetItems();
                foreach (var data in result)
                {
                    using (MyControl mc = new MyControl())
                    {
                        mc.txtUsername.Text = data.username;
                    }
                }
            }
    public MainPage()
          {
              //Constuctor 
              InitializeComponent();
              InitControls();
          }


    Error is that; an object is not set to an instance, which i understand because the objects in MyControl is not yet live on start.

    Please, any idea on how to achieve this?


    • Edited by Godymn Saturday, November 10, 2018 11:09 PM For more understanding
    Saturday, November 10, 2018 3:38 PM

Answers

  • If you are talking about the form's class and the usercontrol's  class, then yes  there are two classes. two objects, in play. 

    The usercontrol is a mini form, in layman terms,  to the hosting main form. The textbox should have been instanced in InitializeComponent(), becuase the textbox is a class too.

    https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.usercontrol?view=netframework-4.7.2

    If I am not mistaken, a static class cannot instance an object. 

    Hi DA924x,

    Please, base on your response, i still don't understand how to fix the problem.

    http://www.dountsis.com/general/how-to-use-user-controls-to-create-mdi-winform-applications.php

    // User Controls
    private UCApplication.UserControls.UCForm1 ucForm1;
    private UCApplication.UserControls.UCForm2 ucForm2;
    Now we need to instantiate the objects and add them to the pool of available controls of MainForm. We modify the class constructor as seen below:
    public MainForm()
    {
    InitializeComponent();
    // Instantiate the User Controls
    ucForm1 = new UCApplication.UserControls.UCForm1();
    this.Controls.Add(ucForm1);
    ucForm2 = new UCApplication.UserControls.UCForm2();
    this.Controls.Add(ucForm2);
    }

    The  InitializeComponent() of the Usercontrol should have initialized any controls such as a textbox control on the Usercontrol, if it does not, then you need to go to the method and initialize the textbox control.

    IMO, you shouldn't have any database logic in any form or usercontol either, which should be using loose coupling that would be implemented by using SoC and SoD.  The form or usercontrol should be dumb as dumb as possible,  and their jobs are to have UI controls that interact with the user with business and data access logic segregated from the form or usercontrol.

     http://www.dotnet-stuff.com/tutorials/c-sharp/understanding-loose-coupling-and-tight-coupling

    https://en.wikipedia.org/wiki/Separation_of_concerns

    You could look into MVP that can be used by a Windows form or a Usercontrol, which would be implementing SoD.  

    https://www.codeproject.com/Articles/228214/Understanding-Basics-of-UI-Design-Pattern-MVC-MVP

    It is something you could think about in looking at the ntier example link where EF would be installed in the Data Access Layer/Data Tier. 

    https://www.codeproject.com/Articles/36847/Three-Layer-Architecture-in-C-NET

    You would use the DTO pattern sending the DTO or DTO(s) through the layers, leaving the EF entities at the DAL and send the DTO.

    https://en.wikipedia.org/wiki/Data_transfer_object

    https://www.codeproject.com/Articles/1050468/Data-Transfer-Object-Design-Pattern-in-Csharp.

    https://docs.microsoft.com/en-us/visualstudio/data-tools/n-tier-data-applications-overview?view=vs-2017

    Of course, you don't have to do what I am saying now, it is just food for thought, and you should concentrate on just getting the usercontrol to work. :)

    But think about architecting .NET solutions effectively from the frontend to the backend. 

    Layered or N-tier.....

    https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ee658117(v=pandp.10)





    • Edited by DA924x Sunday, November 11, 2018 9:49 AM
    • Marked as answer by Godymn Monday, November 12, 2018 2:07 PM
    Sunday, November 11, 2018 9:46 AM

All replies

  • What type of form UI program is this ASP.NET, Windows, WPF or what?

    Do you know what object is a null value object that would throw the exception message/

    It also looks like you are not implementing seperation of duties in using a UI design and loose coupling. 

    Saturday, November 10, 2018 7:37 PM
  • @DA924x

    This is a Winforms - Desktop Program

    The issue lies in the InitControl Method. The textbox on the UserControl form is not live yet because when the app starts, it doesn't open the UserControl form. It only open the MainPage form but i also want the textbox on the other UserControl to be initialized with data from my db.

    There are two classes there, i have modify my code for more clarity

    Appreciate your feedback.


    • Edited by Godymn Saturday, November 10, 2018 11:11 PM
    Saturday, November 10, 2018 11:07 PM
  • If you are talking about the form's class and the usercontrol's  class, then yes  there are two classes. two objects, in play. 

    The usercontrol is a mini form, in layman terms,  to the hosting main form. The textbox should have been instanced in InitializeComponent(), becuase the textbox is a class too.

    https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.usercontrol?view=netframework-4.7.2

    If I am not mistaken, a static class cannot instance an object. 

    Sunday, November 11, 2018 2:55 AM
  • If you are talking about the form's class and the usercontrol's  class, then yes  there are two classes. two objects, in play. 

    The usercontrol is a mini form, in layman terms,  to the hosting main form. The textbox should have been instanced in InitializeComponent(), becuase the textbox is a class too.

    https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.usercontrol?view=netframework-4.7.2

    If I am not mistaken, a static class cannot instance an object. 

    Hi DA924x,

    Please, base on your response, i still don't understand how to fix the problem.

    Sunday, November 11, 2018 8:29 AM
  • If you are talking about the form's class and the usercontrol's  class, then yes  there are two classes. two objects, in play. 

    The usercontrol is a mini form, in layman terms,  to the hosting main form. The textbox should have been instanced in InitializeComponent(), becuase the textbox is a class too.

    https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.usercontrol?view=netframework-4.7.2

    If I am not mistaken, a static class cannot instance an object. 

    Hi DA924x,

    Please, base on your response, i still don't understand how to fix the problem.

    http://www.dountsis.com/general/how-to-use-user-controls-to-create-mdi-winform-applications.php

    // User Controls
    private UCApplication.UserControls.UCForm1 ucForm1;
    private UCApplication.UserControls.UCForm2 ucForm2;
    Now we need to instantiate the objects and add them to the pool of available controls of MainForm. We modify the class constructor as seen below:
    public MainForm()
    {
    InitializeComponent();
    // Instantiate the User Controls
    ucForm1 = new UCApplication.UserControls.UCForm1();
    this.Controls.Add(ucForm1);
    ucForm2 = new UCApplication.UserControls.UCForm2();
    this.Controls.Add(ucForm2);
    }

    The  InitializeComponent() of the Usercontrol should have initialized any controls such as a textbox control on the Usercontrol, if it does not, then you need to go to the method and initialize the textbox control.

    IMO, you shouldn't have any database logic in any form or usercontol either, which should be using loose coupling that would be implemented by using SoC and SoD.  The form or usercontrol should be dumb as dumb as possible,  and their jobs are to have UI controls that interact with the user with business and data access logic segregated from the form or usercontrol.

     http://www.dotnet-stuff.com/tutorials/c-sharp/understanding-loose-coupling-and-tight-coupling

    https://en.wikipedia.org/wiki/Separation_of_concerns

    You could look into MVP that can be used by a Windows form or a Usercontrol, which would be implementing SoD.  

    https://www.codeproject.com/Articles/228214/Understanding-Basics-of-UI-Design-Pattern-MVC-MVP

    It is something you could think about in looking at the ntier example link where EF would be installed in the Data Access Layer/Data Tier. 

    https://www.codeproject.com/Articles/36847/Three-Layer-Architecture-in-C-NET

    You would use the DTO pattern sending the DTO or DTO(s) through the layers, leaving the EF entities at the DAL and send the DTO.

    https://en.wikipedia.org/wiki/Data_transfer_object

    https://www.codeproject.com/Articles/1050468/Data-Transfer-Object-Design-Pattern-in-Csharp.

    https://docs.microsoft.com/en-us/visualstudio/data-tools/n-tier-data-applications-overview?view=vs-2017

    Of course, you don't have to do what I am saying now, it is just food for thought, and you should concentrate on just getting the usercontrol to work. :)

    But think about architecting .NET solutions effectively from the frontend to the backend. 

    Layered or N-tier.....

    https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ee658117(v=pandp.10)





    • Edited by DA924x Sunday, November 11, 2018 9:49 AM
    • Marked as answer by Godymn Monday, November 12, 2018 2:07 PM
    Sunday, November 11, 2018 9:46 AM
  • Hi Godymn,

    According to your description, I am not sure what what cause the issue, could you please share a simple complete code to reproduce the issue. 

    Here is my sample based on your code, which works well.

    #MyControl.

    public partial class MyControl : UserControl
        {
    
            public static MyControl fromMyControl;
            public MyControl()
            {
                InitializeComponent();
            }
    
            private void MyControl_Load(object sender, EventArgs e)
            {
                fromMyControl = this;
            }
    
            private List<item> GetItems()
            {
                using (Model1 db = new Model1())
                {
                    return db.items.ToList();
                }
    
            }
        }

    #Usage:

    public partial class Form1 : Form
        {
    
            void InitControls()
            {
                using (var db = new Model1())
                {
                    var result = db.items.ToList();
                    foreach (var data in result)
                    {
                        MyControl mc = new MyControl();
                        mc.txtUsername.Text = data.username;
                        mc.Dock = DockStyle.Top;
                        this.panel1.Controls.Add(mc);
                    }
                }
                
            }
    
            public Form1()
            {
                InitializeComponent();
    
                InitControls();
            }
        }

    #Database

    CREATE TABLE [dbo].[items] (
        [Id]       INT          IDENTITY (1, 1) NOT NULL,
        [username] VARCHAR (50) NULL
    );
    

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, November 12, 2018 2:29 AM
    Moderator
  • If you are talking about the form's class and the usercontrol's  class, then yes  there are two classes. two objects, in play. 

    The usercontrol is a mini form, in layman terms,  to the hosting main form. The textbox should have been instanced in InitializeComponent(), becuase the textbox is a class too.

    https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.usercontrol?view=netframework-4.7.2

    If I am not mistaken, a static class cannot instance an object. 

    Hi DA924x,

    Please, base on your response, i still don't understand how to fix the problem.

    http://www.dountsis.com/general/how-to-use-user-controls-to-create-mdi-winform-applications.php

    // User Controls
    private UCApplication.UserControls.UCForm1 ucForm1;
    private UCApplication.UserControls.UCForm2 ucForm2;
    Now we need to instantiate the objects and add them to the pool of available controls of MainForm. We modify the class constructor as seen below:
    public MainForm()
    {
    InitializeComponent();
    // Instantiate the User Controls
    ucForm1 = new UCApplication.UserControls.UCForm1();
    this.Controls.Add(ucForm1);
    ucForm2 = new UCApplication.UserControls.UCForm2();
    this.Controls.Add(ucForm2);
    }

    The  InitializeComponent() of the Usercontrol should have initialized any controls such as a textbox control on the Usercontrol, if it does not, then you need to go to the method and initialize the textbox control.

    IMO, you shouldn't have any database logic in any form or usercontol either, which should be using loose coupling that would be implemented by using SoC and SoD.  The form or usercontrol should be dumb as dumb as possible,  and their jobs are to have UI controls that interact with the user with business and data access logic segregated from the form or usercontrol.

     http://www.dotnet-stuff.com/tutorials/c-sharp/understanding-loose-coupling-and-tight-coupling

    https://en.wikipedia.org/wiki/Separation_of_concerns

    You could look into MVP that can be used by a Windows form or a Usercontrol, which would be implementing SoD.  

    https://www.codeproject.com/Articles/228214/Understanding-Basics-of-UI-Design-Pattern-MVC-MVP

    It is something you could think about in looking at the ntier example link where EF would be installed in the Data Access Layer/Data Tier. 

    https://www.codeproject.com/Articles/36847/Three-Layer-Architecture-in-C-NET

    You would use the DTO pattern sending the DTO or DTO(s) through the layers, leaving the EF entities at the DAL and send the DTO.

    https://en.wikipedia.org/wiki/Data_transfer_object

    https://www.codeproject.com/Articles/1050468/Data-Transfer-Object-Design-Pattern-in-Csharp.

    https://docs.microsoft.com/en-us/visualstudio/data-tools/n-tier-data-applications-overview?view=vs-2017

    Of course, you don't have to do what I am saying now, it is just food for thought, and you should concentrate on just getting the usercontrol to work. :)

    But think about architecting .NET solutions effectively from the frontend to the backend. 

    Layered or N-tier.....

    https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ee658117(v=pandp.10)





    Hello DA924x,

    Appreciate your feedback.

    I understand your concerns, yeah thanks man. I already started working on this project before i got to know about MVP. But plans are in place to refactor my codes and implement the MVP model. Thanks again for the concern.

    Looking at the code you provided, it was not what i wanted. I wasn't trying to load a userControl unto a form1 (MDI). The userControl is a different object and components on it like textboxes needs to be initialized with data once form1 loads. The userControl does not need to show once i run the program.

    However, i already figured out a way based on the link you provided. An idea dropped in my head and when i tested, it worked!.

    Will mark this as helpful since it gave me an idea and a leadway to solve the bug.

    Thanks alot.

    Monday, November 12, 2018 2:07 PM
  • Hi Godymn,

    According to your description, I am not sure what what cause the issue, could you please share a simple complete code to reproduce the issue. 

    Here is my sample based on your code, which works well.

    #MyControl.

    public partial class MyControl : UserControl
        {
    
            public static MyControl fromMyControl;
            public MyControl()
            {
                InitializeComponent();
            }
    
            private void MyControl_Load(object sender, EventArgs e)
            {
                fromMyControl = this;
            }
    
            private List<item> GetItems()
            {
                using (Model1 db = new Model1())
                {
                    return db.items.ToList();
                }
    
            }
        }

    #Usage:

    public partial class Form1 : Form
        {
    
            void InitControls()
            {
                using (var db = new Model1())
                {
                    var result = db.items.ToList();
                    foreach (var data in result)
                    {
                        MyControl mc = new MyControl();
                        mc.txtUsername.Text = data.username;
                        mc.Dock = DockStyle.Top;
                        this.panel1.Controls.Add(mc);
                    }
                }
                
            }
    
            public Form1()
            {
                InitializeComponent();
    
                InitControls();
            }
        }

    #Database

    CREATE TABLE [dbo].[items] (
        [Id]       INT          IDENTITY (1, 1) NOT NULL,
        [username] VARCHAR (50) NULL
    );

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Hi Zhanglong,

    Appreciate your response.

    Just like i said to DA924x,  I wasn't trying to load a userControl unto a form1 (MDI). The userControl is a different object and components on it like textboxes needs to be initialized with data once form1 loads. The userControl does not need to show once i run the program.

    However, i already figured out a way based on the link DA924x provided. An idea dropped in my head and when i tested, it worked!.

    Thanks for your willingness to always assist.

    Monday, November 12, 2018 2:11 PM