c# - Delete record from a sql table by selecting from gridview on button click -


i want delete record datagridview that's in 1 form pressing button in form. getting nullreferenceexception unhandled error. new c# if write me correct code appreciate it.

here's got far.

private void button1_click(object sender, eventargs e) {     sqlconnection con = new sqlconnection(@" data source=home-d2cadc8d4f\sql;initial catalog=motociclete;integrated security=true");      sqlcommand cmd = new sqlcommand();     (int = 0; < datagridview1.rows.count; i++)     {         datagridviewrow dr = datagridview1.rows[i];         if (dr.selected == true)         {             datagridview1.rows.removeat(i);             try             {                 con.open();                 cmd.commandtext = "delete motociclete codm=" + + "";                 cmd.executenonquery();                 con.close();             }             catch (exception ex)             {                 messagebox.show(ex.tostring());             }         }     }     this.close(); } 

just invert verse of loop.

 (int = datagridview1.rows.count - 1; >= 0 ; i--) 

in way loop not affected changing number of rows

also. case not open/close connection @ every command execution, , command execution more performant if use parameter in way

using(sqlconnection con = new sqlconnection(@" data source=home-d2cadc8d4f\sql;initial catalog=motociclete;integrated security=true")) using(sqlcommand cmd = new sqlcommand("delete motociclete codm=@id", con)) {     con.open();     cmd.parameters.addwithvalue("@id", 0);     (int = datagridview1.rows.count-1; >= 0; i++)     {         datagridviewrow dr = datagridview1.rows[i];         if (dr.selected == true)         {             datagridview1.rows.removeat(i);             cmd.parameters["@id"].value = i;             cmd.executenonquery();         }     } } 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -