C# ASP.NET Gridview 仅在确认时删除行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9026884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET Gridview delete row only on confirmation
提问by HGomez
I have a gridviewwith the onRowDeletingmethod implemented. I would like to prompt the user with a pop up message to confirm whether they wish to delete this item or not.
If the user clicks "OK", "Confirm" or something similar then I would like the onRowsDeletingto be process and the record deleted. But if the user pressed "No" then I would like the method to be cancelled and the record not deleted.
我有一个实现gridview的onRowDeleting方法。我想通过弹出消息提示用户确认他们是否希望删除此项目。如果用户单击“确定”、“确认”或类似的东西,那么我希望onRowsDeleting处理并删除记录。但是如果用户按下“否”,那么我希望取消该方法并且不删除记录。
How can this be done?
如何才能做到这一点?
Here is my gridviewand onRowDeletingmethod in the code behind.
这是后面代码中的我gridview和onRowDeleting方法。
<asp:GridView runat="server" ID="gvShowQuestionnaires" HeaderStyle-CssClass="table_header" CssClass="view" AlternatingRowStyle-CssClass="alt" AlternatingRowStyle-BackColor="#f3f4f8" AutoGenerateColumns="False"
DataKeyNames='QuestionnaireID' OnRowDeleting="gvShowQuestionnaires_RowDeleting" OnRowEditing="gvShowQuestionnaires_RowEdit" OnSelectedIndexChanged="gvShowQuestionnaires_SelectedIndexChanged" FooterStyle-CssClass="view_table_footer" >
<Columns>
<asp:BoundField DataField="QuestionnaireID" HeaderText="ID" HeaderStyle-Width="80px" ItemStyle-CssClass="bo"></asp:BoundField>
<asp:BoundField DataField="QuestionnaireName" HeaderText="Questionnaire Name" />
<asp:ButtonField CommandName="select" ButtonType="Link" Text="view results" />
<asp:CommandField HeaderText="Options" CausesValidation="true" ShowDeleteButton="True" ShowEditButton="true" EditText="Edit">
</asp:CommandField>
</Columns>
</asp:GridView>
protected void gvShowQuestionnaires_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int questionnaireID = (int)gvShowQuestionnaires.DataKeys[Convert.ToInt32(e.RowIndex)].Value;
GetData.DeleteQuestionnaire(questionnaireID);
gvShowQuestionnaires.DataSource = DT;
gvShowQuestionnaires.DataBind();
lblActivity.Visible = true;
lblActivity.Text = "Your questionnaire has been deleted";
}
采纳答案by Tim Schmelter
You should do that on clientside with javascript.
您应该在客户端使用 javascript 执行此操作。
Therefore you can handle GridView's RowDataBoundevent to add this to the Delete-Button's OnClientClick:
因此,您可以处理 GridView 的RowDataBound事件以将其添加到 Delete-Button 的OnClientClick:
protected void gvShowQuestionnaires_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// reference the Delete LinkButton
LinkButton db = (LinkButton)e.Row.Cells[3].Controls[0];
db.OnClientClick = "return confirm('Are you certain you want to delete this questionnaire?');";
}
}
http://msdn.microsoft.com/en-us/library/bb428868.aspx
http://msdn.microsoft.com/en-us/library/bb428868.aspx
This js-function will return whether the user clicked okor cancel. If a js-eventhandler returns false, the page will not postback to the server.
此 js 函数将返回用户是否单击ok或cancel. 如果 js-eventhandler 返回false,则页面不会回发到服务器。
回答by Bat_Programmer
Another way:
其它的办法:
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.
LinkButton button = control as LinkButton;
if (button != null && button.CommandName == "Delete")
// Add delete confirmation
button.OnClientClick = "return confirm('Are you sure " +
"you want to delete this record?');";
}
}
}
回答by Md. Musa Prodhan
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string id = e.Row.Cells[2].Text;
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton db = (LinkButton)e.Row.Cells[6].Controls[0];
db.OnClientClick = "return confirm('Are you want to delete this Work Description : " + id + "?');";
}
}
回答by Bishoy Hanna
Simply call a JavaScript function returning a boolean by "return" caller so if returns false this link button will not work.
只需通过“返回”调用者调用返回布尔值的 JavaScript 函数,如果返回 false,则此链接按钮将不起作用。
ASPX
ASPX
<asp:LinkButton runat="server" OnClientClick="return DeleteItem();" locationID='<%# DataBinder.Eval (Container.DataItem,"Id").ToString() %>' ID="linkDelete" OnClick="linkDelete_Click" title='<%# "Delete " + DataBinder.Eval (Container.DataItem,"City").ToString() %>' Style="float: left;"><img src="Asset/img/icon/bin.gif" alt="" hspace="3" /></asp:LinkButton>
Javascript
Javascript
<script type="text/javascript">
function DeleteItem() {
if (confirm("Delete this Location?")) {
return true;
} else {
return false;
}
}
</script>
Server Side
服务器端
protected void linkDelete_Click(object sender, EventArgs e)
{
int locationID =0;
int.TryParse(((LinkButton)sender).Attributes["locationID"].ToString(),out locationID);
if (locationID > 0)
{
Location loc = Location.GetById(locationID);
CurrentDataContext.CurrentContext.DeleteObject(loc);
CurrentDataContext.CurrentContext.SaveChanges();
bindGv();
}
}
回答by CoolBreeze
The "return confirm(..") Javascript is on the right track.
“返回确认(..”)Javascript 是在正确的轨道上。
The problem is that ASP.NET will append js to call __doPostBack
问题是ASP.NET会追加js来调用__doPostBack
so you'll get something like this in your HTML for the delete button:
所以你会在你的 HTML 中为删除按钮得到这样的东西:
OnClickClient="return confirm('Are you sure you want to delete this record?');";javascript:__doPostBack('ctl00$Main$PlansGrid','Delete1')"
What happens is: 1) User clicks Delete button. 2) Confirm dialog displayed. 3) User clicks on OK button. 4) Confirm returns True. 5) return at beginning of statement executes and __doPostBack is not called.
会发生什么: 1) 用户点击删除按钮。2) 显示确认对话框。3) 用户点击确定按钮。4) 确认返回真。5) 语句开始处的 return 执行并且不调用 __doPostBack。
The solution is to return only if confirm returns false:
解决方案是仅在确认返回 false 时才返回:
OnClientClick="if(!confirm('Are you sure you want to delete this Plan?')) return;"
If user clicks OK confirm returns True and then __doPostBack executes.
如果用户单击 OK 确认返回 True,然后 __doPostBack 执行。

