Deleting records from GridView and DB using the button (check box and delete button)

I have GridView1 declared as:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" GridLines="None" DataKeyNames="Case_ID"> <Columns> <asp:TemplateField> <ItemTemplate><asp:CheckBox ID="cb" runat="server" /></ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="No."> <ItemTemplate><%# Container.DataItemIndex + 1 %></ItemTemplate> </asp:TemplateField> <asp:BoundField HeaderText="Case Title" DataField="caseTitle"/> <asp:BoundField HeaderText="Age" DataField="age" /> <asp:BoundField HeaderText="Gender" DataField="gender"/> <asp:BoundField HeaderText="Treated By" DataField="owner"/> <asp:BoundField HeaderText="Added Date" DataField="sDate"/> <asp:BoundField HeaderText="" DataField="Case_ID" Visible="false"/> </Columns> </asp:GridView> 

and this is the DataTable that I use as the data source for it

 DataTable aTable = new DataTable(); aTable.Columns.Add("caseTitle", typeof(string)); aTable.Columns.Add("age", typeof(string)); aTable.Columns.Add("gender", typeof(string)); aTable.Columns.Add("owner", typeof(string)); aTable.Columns.Add("sDate", typeof(string)); aTable.Columns.Add("Case_ID", typeof(int)); I want to use Case_ID as an index for the GridView, so I can delete a record from database when I check its check box in the GridView. 

here is the script:

GridView displays information about cases from the database. The user can select the checkboxes and click the [Delete] button; this action should delete records from the database;

When I execute this code in the [Delete] button:

 foreach (GridViewRow row in GridView1.Rows) { CheckBox c = (CheckBox)row.FindControl("cb"); if (c.Checked) { int rowIndex = GridView1.SelectedIndex; string id = GridView1.DataKeys[rowIndex].Value.ToString(); ds.DeleteCommand = " delete from Cases where Case_ID=" + id + ""; ds.Delete(); } } 

I found that c is always null, even when I check for some entries; so the problem is that it does not detect a change in the checkbox, what can I do to make it detect?

0
source share
1 answer

If the delete button ... try to find the feed install button using the "argument" attribute of the delete button. I usually set the identifier of the row that I want to remove as the attribute value of the button argument. Therefore, I never need to look for a checkbox ... (on the client side, I use the click event of the click to update the attribute attribute of the delete button).

Another word is safe: use a stored procedure to avoid security problems (never put the delete statement or any SQL statement - like hard code in C # ...).

EDIT:

check also:

  GridViewRow.RowType==RowType.DataRow 

You get null because the current line is possibly a header line or something like that, and the checkbox is not part of this type.

0
source

Source: https://habr.com/ru/post/1442165/


All Articles