I am trying to delete multiple rows from a GridView but I am struggling to find out if a c开发者_如何转开发heck box was checked.
At the moment my code isn't attempting to delete anything just check which checkboxes were checked and which weren't. My attempt isn't showing any checkboxes as being checked and also seems to loop though the GridView rows twice!
.ASPX
<asp:GridView ID="gvImages" DataKeyNames="id" runat="server" AutoGenerateColumns="False" BorderWidth="0px" GridLines="None">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="imageId" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:ImageField DataImageUrlField="image_path" DataImageUrlFormatString="~/admin/images/{0}"></asp:ImageField>
<asp:BoundField DataField="id" />
</Columns>
</asp:GridView>
<asp:Button
ID="btnMultipleRowDelete"
OnClick="btnMultipleRowDelete_Click"
runat="server"
Text="Delete Rows" />
CODE BEHIND
Protected Sub btnMultipleRowDelete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnMultipleRowDelete.Click
' Looping through all the rows in the GridView
For Each row As GridViewRow In gvImages.Rows
Dim checkbox As CheckBox = CType(row.FindControl("imageId"), CheckBox)
Dim rowID As Integer = Convert.ToInt32(gvImages.DataKeys(row.RowIndex).Value)
'Check if the checkbox is checked.
If checkbox.Checked Then
Response.Write("Deleted" & rowID & "<br />")
Else
Response.Write("Not deleted: " & rowID & "<br />")
End If
Next row
End Sub
Thanks for any help. J.
Are you binding your GridView on Page_Load?
Make sure you have If Not Page.IsPostBack Then
around your binding:
If Not Page.IsPostBack Then
BindGridViewHere
End If
Otherwise, when the button is triggered, the gridview will be rebound, meaning all checkboxes are reset!
精彩评论