2012-08-30 89 views
0

我有以下的GridView現在asp.net添加屬性的GridView CommandField中刪除按鈕

<asp:GridView DataSourceID="odsRooms" DataKeyNames="id,objectid" ID="gvRooms" PageSize="10" runat="server" AutoGenerateColumns="False" > 
<Columns> 
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderStyle-VerticalAlign="Bottom" HeaderText="Name"> 
    <ItemTemplate> 
     <%# Eval("title")%>      
    </ItemTemplate> 
    <EditItemTemplate> 
     <asp:TextBox ID="tbRoomname" MaxLength="20" Text='<%# Bind("title")%>' runat="server" />      
    </EditItemTemplate> 
</asp:TemplateField> 
<asp:CommandField ValidationGroup="updateroom" ShowDeleteButton="true" DeleteText="Delete" ShowEditButton="true" EditText="Edit" CancelText="Cancel" /> 
</Columns>   
</asp:GridView> 

,一切都工作得很好,但是當用戶在CommandField中列出的點擊TE刪除按鈕,該項目將被立即刪除,而不要求確認。 我希望將下列屬性添加到Commandfield的刪除按鈕中: OnClientClick =「javascript:return confirm('您確定要刪除?');」

我該怎麼做?

+1

http://www.codeproject.com/Articles/27083/LinqDataSource-with-ASP-NET-Data-Controls-Part -III通過這個 – naval

回答

5

使用follwoing代碼

protected void gvRooms_RowDataBound(object sender, 
        GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     LinkButton lb = (LinkButton)e.Row.Cells[1].Controls[1]; 
     if(lb != null) 
     { 
      lb.Attributes.Add("onclick", "javascript:return " + 
"confirm('Are you sure you want to delete this record ')"); 
     }  
    } 

}

3

您可以設置已刪除列模板後,您可以使用的OnClientClick命令返回確認之前刪除數據。

<ItemTemplate> 
<asp:ImageButton ID="ImageButton1" runat="server" CausesValidation="False" 
CommandName="Delete" ImageUrl="~/Delete.png" Text="Delete" 
OnClientClick="return confirm('Are you sure to delete data?');" /> 
</ItemTemplate> 
2

ASPX

<asp:CommandField HeaderImageUrl="..\Images\DeleteImg.png" ShowDeleteButton="True" 
      DeleteImageUrl="..\Images\DeleteImg.png" DeleteText="Delete Record" 
      ItemStyle-Font-Size="8pt" ItemStyle-Width="30px" ButtonType="Image"> 
</asp:CommandField> 

.CS

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     // loop all data rows 
     foreach (DataControlFieldCell cell in e.Row.Cells) 
     { 
      // check all cells in one row 
      foreach (Control control in cell.Controls) 
      { 
       // Must use LinkButton here instead of ImageButton 
       // if you are having Links (not images) as the command button. 
       ImageButton button = control as ImageButton; 
       if (button != null && button.CommandName == "Delete") 
        // Add delete confirmation 
        button.OnClientClick = "if (!confirm('Are you sure " + 
          "you want to delete this record?')) return;"; 
      } 
     } 
    } 
}