2011-03-07 85 views
1

我想從GridView中刪除多行,但我很努力地發現是否勾選了一個複選框。Gridview多重刪除

此刻我的代碼並沒有試圖刪除任何東西只是檢查哪些複選框被選中,哪些不是。我的嘗試沒有顯示任何複選框被檢查,並似乎循環兩次GridView行!

.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" /> 

後面的代碼

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 

感謝您的幫助。 J.

回答

1

你是否在Page_Load上綁定了你的GridView?

請確保您有If Not Page.IsPostBack Then在你的綁定:

If Not Page.IsPostBack Then 
    BindGridViewHere 
End If 

否則,當按鈕被觸發時,GridView會反彈,這意味着所有的複選框被重置!

+0

OnRowDeleting?我不是指這個事件。我做了一個非常類似的事情,當刪除多行和重新綁定時發佈回來也抓到我了 – Curt 2011-03-07 17:24:57

+0

謝謝柯特,這似乎是問題.....對不起,我在莫學習!再次感謝。 – JBoom 2011-03-07 17:26:41

+0

不用擔心@JBoom。請標記爲答案:) – Curt 2011-03-07 17:27:41