asp.net将属性添加到gridview命令字段删除按钮

时间:2012-08-30 10:19:20

标签: asp.net gridview

我有以下gridview

<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行中的删除按钮时,该项目会立即删除,而不会要求确认。 我希望将以下属性添加到Commandfield的删除按钮: OnClientClick =“javascript:return confirm('你一定要删除?');”

我该怎么办?

3 个答案:

答案 0 :(得分: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 ')");
       }      
   }

}

答案 1 :(得分: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 :(得分: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;";
            }
        }
    }
}