Results 1 to 4 of 4

Thread: C# read data source from other form

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Jul 2009

    C# read data source from other form

    how can i make the connection avalible for form2 too for database

    In form1: i have connection to sql database
    and i want it to be enabled connection for Form2 too so i dont need to write again textboxes and fields for connect to db again how can i do it?

    in form2 :

    SqlConnection con = new SqlConnection("");
    how to connect it to form1 ?
    any ideas?

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Sydney, Australia

    Re: C# read data source from other form

    If you want to write data access code once then you put it in a dedicated class and not in forms. You then use that class in the forms.

  3. #3
    Junior Member
    Join Date
    Feb 2014

    Re: C# read data source from other form

    You need to get the instance of form.

    public static Form GetInstanceOf<T>() where T: Form {
        foreach (Form openForm in Application.OpenForms) {
                if (openForm.GetType() == typeof(T)) {
                        return openForm;
        return null;
    MyForm myForm = GetInstanceOf<MyForm>();
    if(myForm != null)
       SqlConnection con = new SqlConnection(myForm.connectionString);
    Last edited by Guilherme Santos; Feb 13th, 2014 at 02:20 PM.
    C#/VB.NET Themes/Open Source Projects:

  4. #4
    Fanatic Member venerable bede's Avatar
    Join Date
    Sep 2002
    The mystic land of Geordies

    Re: C# read data source from other form

    jmcilhinney is right (as usual) :-). You should keep all you data access code separate from your UI.
    If however you have to do it this way then you could always pass the connection object into the constructor of the new form.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Click Here to Expand Forum to Full Width