Hi all,

when i execute it gives me this exception.
I am trying but i coudnt slove.
Plz help me.

InvalidOperationException
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.

it points to this line -> "int executed = com.ExecuteNonQuery();"
this is my code:

try
            {

                DateTime dt = DateTime.Now;
                CN = new SqlConnection(concString);
                CN.Open();
                String qry = "update BookMaster set Cat_code=" + int.Parse(Cat) + " Title='" + title + "' Publisher='" + Pub + "' No_Of_Pages=" + int.Parse(Page) + " No_Of_Cops=" + int.Parse(Copes) + " Date='" + dt.ToString() + "' price=" + int.Parse(Price) + " year_of_pub=" + int.Parse(Year) + " where Book_ID='" + GetBookId() + "'";

                SqlCommand com = new SqlCommand(qry, CN);
                int executed = com.ExecuteNonQuery();

                
                    if (executed == 1)
                    {
                        MessageBox.Show("Successfully inserted to the database");
                        
                    }

                    else
                    {
                        MessageBox.Show("Insertion failed");
                    }

                

            }
            catch (SqlException ex)
            {
                MessageBox.Show("A SqlException. You must check the Querry parameteres");
                MessageBox.Show(ex.ToString());

            }
            finally
            {
                CN.Close();


            }

realy it gives an error. use comma(,) for separate fields....
correct way

string sql="update tbl_employee set name='"+name+"', address='"+txtAdd.Text+"' where empNo=""+lbtID.Text+"'";

realy it gives an error. use comma(,) for separate fields....
correct way

string sql="update tbl_employee set name='"+name+"', address='"+txtAdd.Text+"' where empNo=""+lbtID.Text+"'";

realy it gives an error. use comma(,) for separate fields....
correct way

string sql="update tbl_employee set name='"+name+"', address='"+txtAdd.Text+"' where empNo=""+lbtID.Text+"'";

Oh how fool iam.
thank you

CN.Open();

put it before int

executed = com.ExecuteNonQuery();

your error is no connection so the problem is in connection string.


i use update like this

string sql=("UPDATE Users SET firstname="+"'"+textBox9.Text+"'"+","+" lastname="+"'"+textBox10.Text+"'"+","+" Username="+"'"+textBox1.Text+"'"+","+"[Password]="+"'"+textBox2.Text+"'", conn)

correct me if im wrong hehe

why do you use firstname="+"'"+textBox9.Text

there were additionally "+" mark. it also correct. but + mark is doing concating string.
no need to add "+".

it works now.
i just put CN.open(); before int int executed = com.ExecuteNonQuery();

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.