Link to home
Start Free TrialLog in
Avatar of wilko100
wilko100

asked on

Delete from datagridview selected row

How you...
1) highlight a row in a datagridview
2) delete from both the gridview and the db

I have done most of the code but im struggling on the last bit that i commented on the code with a question mark
//Select from Contact table
                        SqlDataAdapter da2 = new SqlDataAdapter("SELECT * FROM Contact WHERE CustomerCounter = " + form.Counter + "", cn);                     
                                    
                        da2.TableMappings.Add("Table", "Contact"); 
                        //Delete from Contact table
                        SqlCommand cmdDelete = cn.CreateCommand();
                        cmdDelete.CommandType = CommandType.Text;
                        cmdDelete.ComandText = ("DELETE FROM Contact WHERE CustomerCounter = "+Counter from SelectedRow+"");//what can i use here??
                        da2.DeleteCommand = cmdDelete;                  
                        da2.Fill(ds); 
                        cn.Open();
                        cmdDelete.ExecuteNonQuery();

Open in new window

Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

I believe the approach above is a bit wrong.

You select using ""SELECT * FROM Contact WHERE CustomerCounter = " + form.Counter + """
This means that ALL records have the same CustomerCounter value.

Therefore the statement
"DELETE FROM Contact WHERE CustomerCounter = "+Counter from SelectedRow+"" will not work.
You need to find some other criteria for your delete statement.
Avatar of wilko100
wilko100

ASKER

I have to have the select statement like this as the contacts are linked to customers using the customer counter, for example one customer may have 4 contacts against it. However the contacts do have a unique counter against each person.
 So what your saying is there is no way of destinguishing which record to delete? Im really new to datgridview. I thought there would be something that detects which row you have selected then delete Contact Where Counter = CustomerCunter from selectedRow?. So its all down to the SQL delete statement?
ASKER CERTIFIED SOLUTION
Avatar of wilko100
wilko100

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial