Reputation: 21
My connection button works..
private void connectBtn_Click(object sender, EventArgs e) { username = initialTf.Text; adress = adressTf.Text; connect conn = new connect(); conn.myConnection(username, adress); }
Refering to this method
public SqlConnection myConnection(string dbName, string addr) { connector = new SqlConnection( "Data Source=" + addr + ";" + "Initial Catalog=" + dbName + ";Trusted_Connection=yes;"); try { connector.Open(); MessageBox.Show("Du är ansluten"); } catch (Exception e) { MessageBox.Show("Fail" + e); } return connector;
And then I added another button reading from a textField that will execute a SQL command. Problem is I don't know how to get and use the connection method.
The button code
private void askBtn_Click(object sender, EventArgs e) { sqlQuestion = sqlQuestiontF.Text; connect conn = new connect(); conn.askSQL(sqlQuestion); }
And finally the code in the connect class
> class connect
> {
> SqlConnection connector;
> SqlDataReader rdr = null;
>
> public void askSQL (string sqlQuestion)
> {
>
> SqlCommand cmd = new SqlCommand();
> cmd.CommandText = sqlQuestion;
> cmd.Connection = connector;
> try
> {
> rdr = cmd.ExecuteReader();
> while (rdr.Read())
> {
>
> }
>
> }
> catch (Exception e)
> {
> MessageBox.Show("Fel vid anslutningen!" + e);
> }
> }
My error message is saying that the connection hasn't been properly initalized. Sorry for grammar misstakes and my confusion. Completely new to programming :)
Upvotes: 2
Views: 146
Reputation: 41
I think you missed the connector.Open() in the code.
class connect
{
SqlConnection connector;
SqlDataReader rdr = null;
public void askSQL(string sqlQuestion)
{
try
{
using (connector = new SqlConnection("Your Connection String here"))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = sqlQuestion;
cmd.Connection = connector;
rdr = cmd.ExecuteReader();
using (rdr)
{
while (rdr.Read())
{
}
}
}
}
catch (Exception ex)
{
if (connector.State == System.Data.ConnectionState.Open)
connector.Close();
MessageBox.Show("Fel vid anslutningen!" + e);
}
}
}
Upvotes: 0
Reputation: 936
In your second button click event you are declaring another connect object. This is not the same as the one in your first button. The askSQL() method is expecting the connection to already be initialised. To do this you must run the first button code in the second button event.
private void askBtn_Click(object sender, EventArgs e)
{
sqlQuestion = sqlQuestiontF.Text;
username = initialTf.Text;
adress = adressTf.Text;
connect conn = new connect();
conn.myConnection(username, adress);
conn.askSQL(sqlQuestion);
}
Upvotes: 1