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);
}
}
}
}
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:
Hope it helps,
Mitja