GridView USES CommandField to delete columns prompting a confirmation box

  • 2020-06-23 00:09:52
  • OfStack

When GridView USES CommandField delete, a prompt box will pop up. In the GridView provided by.es2EN2005, we can directly add an CommandField delete column: < asp:CommandField ShowDeleteButton="True" / > , and then finish deleting it in its RowDeleting event. However, in most cases, when we do this kind of deletion, we need to ask the operator to confirm again before deleting, so as to avoid the error caused by the wrong operation.

You can add a confirmation dialog to GridView before deleting it by doing the following.

First, click "Columns" in the Properties dialog box of GridView to enter its Fields designer. Next, select the CommandField Delete column that was previously added in the Field designer, and you will see an item under its properties list that says "Convert this segment to TemplateFied." Click convert to TemplateFied column.

After exiting the field Designer, switch to the source view and you will find that the column has been changed from the original: < asp:CommandField ShowDeleteButton="True" / >
To:
 
<asp:TemplateField ShowHeader="False"> 
<ItemTemplate> 
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" Text=" delete "></asp:LinkButton> 
</ItemTemplate> 

Finally, in < asp:LinkButton > Add: OnClientClick="return confirm(' Confirm to delete? ');"

When you click delete, the client will first pop up "Are you sure you want to delete? Dialog box and the original code written in the RowDeleting event will not be changed at all.

The second method:

Implementation method:

Double-click the OnRowDataBound event for GridView;

Add the code to the GridView1_RowDataBound() method in the background, and the final code looks like this:
 

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
// If it's a bound data row  
if (e.Row.RowType == DataControlRowType.DataRow) 
{ 
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate) 
{ 
((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("onclick", "javascript:return confirm(' You are sure to delete: \"" + e.Row.Cells[1].Text + "\" ? ?')"); 
} 
} 

} 

These are the two most common ways to perfect the removal of controls in GridView, which do not yet implement binding to specific data.

Related articles: