Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i used this code:

C#
SqlConnection Conn = new SqlConnection(@"server=.\Mssql2008;database=Basij;integrated security=true;");
           SqlCommand delcmd = new SqlCommand();
           if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
           {
               delcmd.CommandText = "DELETE FROM Tblregister WHERE Fldcode=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
               Conn.Open();
               delcmd.ExecuteNonQuery();
               Conn.Close();
               dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
           }


but when i click button1 this error apear:
ExecuteNonQuery: Connection property has not been initialized.
Posted
Updated 31-Jul-11 15:51pm
v2

Little modify your code.
you write your code like:-
SqlConnection Conn = new SqlConnection(@"server=.\Mssql2008;database=Basij;integrated security=true;");
SqlCommand delcmd = new SqlCommand();
if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
{
delcmd.CommandText = "DELETE FROM Tblregister WHERE Fldcode=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
Conn.Open();
delcmd.Connection=Conn;//this point is missing in your code.
delcmd.ExecuteNonQuery();
Conn.Close();
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
}
 
Share this answer
 
v2
Comments
walterhevedeich 31-Jul-11 21:53pm    
Spot on. My 5.
As Rakesh have pointed out, you need to specify which connection your data command will use. You might find this[^] useful.
 
Share this answer
 
Hi Rakesh is Right and you can also use this code:

SqlConnection Conn = new SqlConnection(@"server=.\Mssql2008;database=Basij;integrated security=true;");
SqlCommand delcmd = new SqlCommand("DELETE FROM Tblregister WHERE Fldcode=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "",Conn);
if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
{
Conn.Open();
delcmd.ExecuteNonQuery();
Conn.Close();
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
}
 
Share this answer
 
v2
Comments
RaviRanjanKr 1-Aug-11 2:05am    
Always wrap your code in "pre" tag

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900