6TTW014
6TTW014

Reputation: 627

C# Can I Make an sqlConnection public and refer to it from other forms?

I have an sqlConnection on my first form and wondered if I could make it public so I could refer to it from other forms. The code I have so far is below, but I don't know where I would make it public or how.

public partial class frmConnect : Form
{

    public frmConnect()
    {
        InitializeComponent();
    }

    private void btnConnect_Click(object sender, EventArgs e)
    {
        String server;

        server = cmbConnect.SelectedItem.ToString();

        MessageBox.Show(server);

        sqlConnectionNW.ConnectionString = "Data Source=" + server + ";Initial Catalog=Northwind;Integrated Security=True";

        try
        {
            sqlConnectionNW.Open();

            MessageBox.Show("Successfully Connected!");

            frmSignIn frmLogIn = new frmSignIn();

            frmLogIn.server = server;

            sqlConnectionNW.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);

        }

    }
}

}

Upvotes: 2

Views: 4496

Answers (3)

Mitja Bonca
Mitja Bonca

Reputation: 4546

I would suggest you not to do it this way. For accessing to the dataBase its best to use its own class, where you will have all the methods which will interact with the dataBase (select, insert, update and delete queries). And every single method will have its own SqlConnection instantiation (creation of the new object).

You can do it like:

public class WorkWithDataBase
{
    private void SomeMethod()
    {
        using(SqlConnection sqlConn = new SqlConnection("connectionString"))
        {
            //rest of the code
            sqlConn.Open(); //if needed)
            //and no need to close the connection, becuase "using" will take care of that!
        }
    }
}

Hope it helps, Mitja

Upvotes: 4

Morten
Morten

Reputation: 3854

You should extract the connection and all the handling out from the form into its own class -- you could call it DataHandling. Pass this into the form and whereever you want to use it.

:-)

Upvotes: 0

LukeH
LukeH

Reputation: 269508

I'm assuming that your connection object is being held in a field or property of the class. It's generally not a good idea to do that, even if the field or property is private.

Best practice is to keep your connections as local variables where they're needed. Open them as late as possible and close them as early as possible, preferably by wrapping them in a using block.

Upvotes: 1

Related Questions