Connection was not closed. Connection's current state is open - c#

It gives the error connection was not closed. Connection's current state is open.
Please help out with the code.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\vicky\Desktop\Gym management system\Fitness_club\vicky.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * FROM [plan] where plantype='" + comboBox1.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string amount = dr.GetString(1);
textBox5.Text = amount;
}
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}

You should be using using blocks to help with managing your objects.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string connStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\vicky\Desktop\Gym management system\Fitness_club\vicky.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
string cmdText = "Select * FROM [plan] where plantype=#planType";
using (SqlConnection con = new SqlConnection(connStr))
using (SqlCommand cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = cmdText;
cmd.Parameters.AddWithValue("#planType", comboBox1.Text);
var reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
if (reader.Read())
{
string amount = reader.GetString(1);
textbox5.Text = amount;
}
}
}
Also note the use of parameterized queries to avoid SQL injection attacks. Since you are probably only expecting one value to be returned, you should specify the name of the column in the query and use ExecuteScalar instead of the reader and the while loop. The other alternative is to use CommandBehavior.SingleRow as the parameter to the command, which tells the command to just return a single row result.
You also have a cross-threading problem here, and you can solve it by using some invoking.
string amount = string.Empty;
if (reader.Read())
{
amount = reader.GetString(1);
}
if (this.InvokeRequired)
this.Invoke((MethodInvoker) delegate { textbox5.Text = amount; });
else
textbox5.Text = amount;
Another thing to note, is to give your controls meaningful names. Its a lot easier to debug or understand a control named cbx_PlanType than combobox1, or tbx_PlanAmount rather than textbox5.

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\vicky\Desktop\Gym management system\Fitness_club\vicky.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * FROM [plan] where plantype='" + comboBox1.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string amount = dr.GetString(1);
textBox5.Text = amount;
}
// check if connection is open
if (con.State == 1)
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// check if connection is open
if (con.State == 1)
con.Close();
}
}

Related

updating sql server database using c# in asp.net

There isn't any compile error but the database doesn't get updated at all. what is wrong with the code?
protected void Page_Load(object sender, EventArgs e) {
rno.Text = Request.QueryString["rno"];//rno is a textbox
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "select fname from table1 where rno = #rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#rno", rno.Text.Trim());
SqlDataReader reader = command.ExecuteReader();
if (reader.Read()) {
fname.Text = reader["xcountry"].ToString().Trim(); //fname is a textbox
}
reader.Close();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}
protected void modify_Click(object sender, EventArgs e) {
fName.ReadOnly = false;
}
protected void savechanges_Click(object sender, EventArgs e) {
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update table1 set fname=#fname where rno = #rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#fname", sfname);
command.Parameters.AddWithValue("#rno", rno.Text.Trim());
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}
I have tried your code which executed fine and updated database table as well.
I have tried like below :
string connectionString = #"data source=MS-KIRON-01;initial catalog=TestDatabase;integrated security=True;MultipleActiveResultSets=True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update TestTable set fname=#fname where rno =rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#fname", "Test");
command.Parameters.AddWithValue("#rno", "rno");
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
Another way I have tried.
using (SqlConnection connection = new SqlConnection(connectionString ))
{
connection.Open();
var queryText = "UPDATE TestTable SET fname = '" + requestPram.fname + "' WHERE rno ='" + requestPram.rno + "'";
using (SqlCommand cmd = new SqlCommand(queryText, connection))
{
responseResults = await cmd.ExecuteNonQueryAsync();
}
connection.Close();
}
Hope it would help
After searching for a while, I found out that this code was executing perfectly. The only problem was that everything was inside the page_Load() method and thus the page was reloading everytime I updated the database and thus removing the small window to edit the textboxes. The appropriate solution was to associate this code with some button event rather than with the page_Load() event.

quiz with choices using datareader. clicking button to change from number 1 to 4

click a button to change the question in my Form and choices.. but this code only shows the last data of my table when i click it
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=JOSHMAV-PC\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT * "+
"FROM question", conn);
try
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//MessageBox.Show(reader["C1"].ToString());
ques.Text = reader["ques"].ToString();
radioButton1.Text = reader["C1"].ToString();
radioButton2.Text = reader["C2"].ToString();
radioButton3.Text = reader["C3"].ToString();
radioButton4.Text = reader["C4"].ToString();
}
reader.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
im only starting in sql server
you should add some int type of data and you should check it from you sql statement then
you can get your willing data from database it something like this
don't forget to increment it in somewhere of you program and keep in mind of boundary of it
SqlConnection conn = new SqlConnection("Data Source=JOSHMAV-PC\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT * "+
"FROM question where id ="+one, conn);
public class Form1
{
private SqlConnection conn;
private SqlCommand command;
private SqlDataReader reader;
public Form1()
{
conn = new SqlConnection("Data Source=JOSHMAV-PC\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
command = new SqlCommand("SELECT * "+ "FROM question", conn);
try
{
conn.Open();
reader = command.ExecuteReader();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (reader.Read())
{
//MessageBox.Show(reader["C1"].ToString());
ques.Text = reader["ques"].ToString();
radioButton1.Text = reader["C1"].ToString();
radioButton2.Text = reader["C2"].ToString();
radioButton3.Text = reader["C3"].ToString();
radioButton4.Text = reader["C4"].ToString();
}
else reader.Close();
}
}

Retrieve Database values and show them on form using SQLDataReader

I am trying to retrieve data from a Database and show them on a form; but my code isn't working... I've got no errors, and logically it seems to work (to me) so I cannot figure out where I have gone wrong. That's where I need your help!
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
The 'tableListBox' is populated with all the values in column 'Default_Name'. I want it so that when the 'Default_Name' is selected from the list box it shows the values, in textboxes and comboboxes, that correspond with that row in the Database.
Any and all help would be appreciated. Thanks.
I'm going to start by changing your design a bit and suggest that perhaps you look at using a datatable and then just retrieving the rows from the datatable.
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
private DataTable dataTable;
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
foreach(DataRow row in dataTable.Rows)
{
textBox1.Text = row[2].ToString();
comboBox1.Text = row[3].ToString();
comboBox3.Text = row[4].ToString();
textBox2.Text = row[6].ToString();
comboBox2.Text = row[7].ToString();
comboBox4.Text = row[8].ToString();
}
da.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
I generally find that DataTables are more reliable than looping through the actual reader. Ofcourse this assumes that there is data being returned. Also try changing your select statement to this
string Query = "SELECT * FROM [Table]"
If that works, then the problem could be
There is no default name of the specified value or
tableListBox.SelectedValue is not returning any value, in which case, have a look at your listbox selected value
Thanks to Takarii for helping. I figured out who to make it work.
private void tableListBox_SelectedValueChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE ID = '" + tableListBox.SelectedIndex.ToString() + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
First I changed the void to 'SelectedValueChanged' and then I changed the 'WHERE' in the connection Query to the Row Index associated with the selected Value.
Thanks for everyone's help!

The error says "The ConnectionString property has not been initialized" in c#

this code is for the combo box where i want to select some index to show it to my textboxes.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
cmd.Connection = conn;
string query = "SELECT * FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'";
db.connectDB();
db.da.SelectCommand = new OleDbCommand(query, db.conn);
db.executeQryCommand(query, false);
maxRecord = db.ds.Tables[0].Rows.Count;
loadRecords(recordCounter);
cmd.CommandText = query;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr["Gname"].ToString();
textBox2.Text = dr["Gcontactno"].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}
//My program is completely running but not in this section. :(
Is you made an connection between your application and database source using conn object ? You might be used conn object as a connection object but before this was you initialized you Connection ?
Simpy use like
"SqlConnection conn=new SqlConnection("Connection_Source");"
here is your error.
You have to define the connection string for the connection, here i suggest you one best method for executing command.
using (OleDbConnection conn = new OleDbConnection("yourconnectionString"))
{
conn.Open();
using (OleDbCommand cmd =new OleDbCommand("your query text", conn))
{
// execute your command
}
}
If its just to select value from comboBox and display in textBox , then below code will help you...
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT Gname,Gcontactno FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'", conn);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}

Avoid sql injection with calling function

I try to call function to select data from database,coz it will more efficient and i don't like to open connection and execute reader every time,have any solution can do like that?
this is my first method to select data from database,but will hit sql injection problem
protected void Button1_Click(object sender, EventArgs e)
{
Class1 myClass = new Class1();
lblAns.Text = myClass.getdata("Table1", "Student", "Student = '" + TextBox1.Text + "'");
}
public string getdata(string table,string field,string condition)
{
SqlDataReader rdr;
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
string sql = "select " + field + " from " + table + " where " + condition;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return "true";
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
return "false";
}
this is my second method but will hit error (ExecuteReader requires an open and available Connection. The connection's current state is closed.) at line (rdr = cmd.ExecuteReader();)
public string getdata(SqlCommand command,SqlConnection conn)
{
SqlDataReader rdr;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd = command;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return "true";
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Select Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
return "false";
}
public SqlConnection conn()
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
return conn;
}
protected void Button1_Click(object sender, EventArgs e)
{
Class1 myClass = new Class1();
string strSql;
strSql = "Select student from Table1 where student=#stu";
SqlCommand command = new SqlCommand(strSql, myClass.conn());
command.Parameters.AddWithValue("#stu", TextBox1.Text);
myClass.getdata(command, myClass.conn());
}
have solution can use 1st method but will not hit the sql injection problem?
Use ALWAYS the second solution. The only way to avoid Sql Injection is through the use of parameterized queries.
Also fix the error on the second example. You don't associate the connection to the command, also it is a bad practice to keep a global object for the connection. In ADO.NET exist the concept of Connection Pooling that avoid the costly open/close of the connection while maintaining a safe Handling of these objects
public string getdata(SqlCommand command)
{
// Using statement to be sure to dispose the connection
using(SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
cmd.Connection = conn;
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return "true";
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Select Error:";
msg += ex.Message;
return msg;
}
}
return "false";
}

Categories

Resources