I am new to .Net and C# and I have been struggling to get my head round on how to utilise a sql connection created in one section of the code and use it in another. I got 2 buttons on my form. One connects to the database and the other inserts to a table. How do I use the connection variable when inserting to the table?
I hope this makes sense. Thanks
namespace SQL
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
SqlOperations connect = new SqlOperations();
connect.connectToSQL("server=localhost\\SQLExpress;", "database=Cromwell; ");
}
private void btnAddToDatabase_Click(object sender, EventArgs e)
{
SqlOperations addToTable = new SqlOperations();
addToTable.InsertToTable("InputDir", "C:\\");
}
}
public class SqlOperations
{
public bool connectToSQL(string sqlHost, string database)
{
SqlConnection SqlConnect = new SqlConnection("user id=userid;" +
"password=validpassword;" + sqlHost +
"Trusted_Connection=yes;" +
database + "connection timeout=30");
try
{
SqlConnect.Open();
MessageBox.Show("Connected to SQL Express");
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}
public bool InsertToTable(string columnName, string value)
{
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = **SqlConnect**; // THIS BIT COMPLAINS
myCommand.CommandText = "INSERT INTO Config (" + columnName + ") " +
"Values ('" + value + "')";
}
}
}