0

我有以下网格视图

<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 行中的删除按钮时,该项目会立即删除而无需确认。我希望将以下属性添加到命令字段的删除按钮: OnClientClick="javascript:return confirm('You sure to delete?');"

我该怎么做?

4

3 回答 3

5

使用以下代码

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 ')");
       }      
   }

}

于 2012-08-30T10:24:41.667 回答
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>
于 2012-12-12T03:03:36.780 回答
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;";
            }
        }
    }
}
于 2013-11-19T07:59:43.480 回答