Previously in order to delete my record i will use double click, but when it comes to tablet or phone the double click will identify as zoom in / zoom out, therefore i change to onclick with confirmation message and here comes the problem, how should i delete it after user press ok?
P/S: I didn't use button but by selecting the row to delete the data
current onclick code
e.Row.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this order? ');");
Previous doubleclick delete code
//e.Row.Attributes.Add("ondblclick", "__doPostBack('CView','Select$" + e.Row.RowIndex + "');");
the full code of it
protected void CView_RowDataBound(Object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#cccccc'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
e.Row.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this order?');");
//e.Row.Attributes.Add("ondblclick", "__doPostBack('CView','Select$" + e.Row.RowIndex + "');");
}
}
I'm still searching the answer through google. If someone else asked the same question before do share me the link. Thank you
If below line deletes the row from gridview
e.Row.Attributes.Add("ondblclick", "__doPostBack('CView','Select$" + e.Row.RowIndex + "');");
and you want to call above functionality on confirmation then you can do following changes.
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#cccccc'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
e.Row.Attributes.Add("onclick", "var vconfirm = confirm('Are you sure you want to delete this order?'); if (vconfirm){ __doPostBack('CView','Select$" + e.Row.RowIndex + "');}");
}
Just try to assign the OnclientClick in aspx code for the button as follows
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="deletebtn" runat="server" CommandName="Delete"
Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this order? ');" />
</ItemTemplate>
</asp:TemplateField>
Try the following code
<asp:GridView ID="GridView1" runat="server" OnRowDeleting="OnRowDeleting" AutoGenerateColumns = "false" OnRowDataBound = "OnRowDataBound">
<Columns>
<asp:BoundField DataField="..columnname.." HeaderText="...." />
<asp:BoundField DataField="..columname.." HeaderText="...." />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
Then on Row DataBound
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string item = e.Row.Cells[0].Text;
foreach (Button button in e.Row.Cells[2].Controls.OfType<Button>())
{
if (button.CommandName == "Delete")
{
button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + item + "?')){ return false; };";
}
}
}
}
Then on row deleting
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
// delete code
int index = Convert.ToInt32(e.RowIndex);
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[index].Delete();
ViewState["dt"] = dt;
BindGrid();
}
Related
I have this asp.net control:
<div class="field" style="text-align: center;">
<asp:GridView ID="gvTags" runat="server" AutoGenerateColumns = "false"
OnRowDataBound="OnRowDataBound" OnRowDeleting="OnRowDelete">
<Columns>
<asp:BoundField DataField="tagId" HeaderText="Id" />
<asp:BoundField DataField="name" HeaderText="<%$ Resources:Common, tlblTags %>" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
</div>
And I bind my datasource like this from a collection retrieved from database:
this.gvTags.DataSource = product.Tags;
this.gvTags.DataBind();
In the OnRowDataBound I create a popup to show up when the delete button is clicked, so the code is this:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string item = e.Row.Cells[1].Text;
foreach (Button button in e.Row.Cells[2].Controls.OfType<Button>())
{
if (button.CommandName == "Delete")
{
button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + item + "?')){ return false; };";
}
}
}
}
This is working fine, I can see the three rows in my browser and all works as expected (the popup is showing with the correct information etc). But the problem is when I accept the popup so the OnRowDelete event is fired.
I want to remove a Tag from the database with a specific tagId, so I need to get the position 0 at the current row, so this is my code to do that:
protected void OnRowDelete(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
GridViewRow row = this.gvTags.Rows[index];
long tagId = Convert.ToInt64(row.Cells[0].Text);
/* Remove the tag */
productService.RemoveTag(productId, tagId);
/* Delete the row from gridview */
this.gvTags.DeleteRow(index);
}
The error I'am getting is in this line: GridViewRow row = this.gvTags.Rows[index];. I'm getting System.ArgumentOutOfRangeException but I don't understand why. The index variable takes a valid int value like 0, 1...
Any ideas on what I'am doing wrong? Thanks.
I have a GridView and for one of the columns I'm using a drop down list that displays a list of users:
<asp:GridView style="float:left"
ID="gvBookings"
ShowHeaderWhenEmpty="true"
CssClass="tblResults"
runat="server"
OnRowDataBound="gvBookings_RowDataBound"
DataKeyField="ID"
AutoGenerateColumns="false"
allowpaging="false"
<Columns>
<asp:BoundField DataField="FinishDate" HeaderText="Finish Date"></asp:BoundField>
<asp:TemplateField HeaderText="Time Spent By">
<ItemTemplate>
<asp:DropDownList id="ddlUsers" runat="server" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In the code behind I need to call a function that updates the database when the drop down list is changed. I have done this already for the FinishDate column so is there a similar way to do this for the drop down menu?
Code behind:
protected void gvBookings_RowDataBound(object sender, GridViewRowEventArgs e)
{
BHTaskClass.BookingTask booking = (BHTaskClass.BookingTask)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (TableCell c in e.Row.Cells)
{
if (count == 1)
{
string FinishTime = booking.FinishTime.HasValue ? booking.FinishTime.Value.ToString("hh':'mm") : "";
c.Text = "<input type=\"text\" id=\"txtFinishTime" + booking.ID + "\" style=\"width:70px\" type=\"text\" onblur=\"UpdateFinishTime(" + booking.ID + ",this.value)\" value=\"" + FinishTime + "\" >";
}
if (count == 2)
{
ddlUsers.SelectedValue = booking.TimeSpentName;
}
count++;
}
}
}
So when the FinishDate textbox is changed it calls the UpdateFinishTime function and this updates the database. How do I call a function for the drop down list?
ASPX
<asp:DropDownList id="ddlUsers" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="YourFunction_Changed">
</asp:DropDownList>
Code behind:
protected void YourFunction_Changed(object sender, EventArgs e)
{
//do stuff...
}
To get the Row ID you can do it as below
protected void YourFunction_Changed(object sender, EventArgs e)
{
//do stuff...
int Index = ((GridViewRow)((sender as Control)).NamingContainer).RowIndex;
// your logic follows based on the Index
}
Code Behind
public void lbDelete_Click(object sender, EventArgs e)
{
LinkButton lb = sender as LinkButton;
GridViewRow gvrow = lb.NamingContainer as GridViewRow;
gvsize.DeleteRow(gvrow.RowIndex);
}
GridView:
<asp:GridView ID="gvsize" runat="server" ShowFooter="True" CellPadding="1" CellSpacing="2" AutoGenerateColumns="false" GridLines="Horizontal">
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkdelete" runat="server" ForeColor="Blue" OnClick="lbDelete_Click">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView >
There are 2 rows in my gridview which I need to delete the row using the function above.
It throws an error "gvsize" RowDeletingEvent was not handled properly.
Is that necessary to use OnRowDeleted/OnRowDeleting in gridview which I feel not necessary??
As stated in How to delete row from gridview?
You are deleting the row from the gridview but you are then going and
calling databind again which is just refreshing the gridview to the
same state that the original datasource is in.
Either remove it from the datasource and then databind, or databind
and remove it from the gridview without redatabinding.
You can use row databound event to accomplish this task.
<asp:LinkButton ID="lnkBtnDel" runat="server" CommandName="DeleteRow" OnClientClick="return confirm('Are you sure you want to Delete this Record?');"">Delete</asp:LinkButton>
and in the rowdatabound event you can have
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
//incase you need the row index
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
//followed by your code
}
}
Try this to delete row
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
dt.Rows.RemoveAt(e.RowIndex);
GridView1.DataSource = dt;
GridView1.DataBind();
}
You can also delete row from another method using Template Column
ASPX
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="imgDelete" runat="server" CommandName="deletenotice" ImageUrl="~/images/delete1.gif" alt="Delete"
OnClientClick="return confirm('Are you sure want to delete the current record ?')">
</asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
C# Code
protected void gvNoticeBoardDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToLower().Equals("deletenotice"))
{
GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
NoticeBoard notice = new NoticeBoard();
HiddenField lblCust = (HiddenField)row.FindControl("hdngvMessageId");//Fetch the CourierId from the selected record
auditTrail.Action = DBAction.Delete;
Service simplyHRClient = new Service();
MessageClass messageClass = simplyHRClient.SaveNoticeBoard(notice, auditTrail);
if (messageClass.IsSuccess)
{
this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
showSummary.Style["display"] = string.Empty;
showSummary.Attributes["class"] = "success-message";
if (messageClass.RecordId != -1)
lblCust.Value = messageClass.RecordId.ToString();
}
else
{
this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
showSummary.Style["display"] = string.Empty;
showSummary.Attributes["class"] = "fail-message";
}
//Bind Again grid
GetAllNoticeBoard();
}
}
Hope it helps you
I want to prompt the user for confirmation when he tries to delete a record in a detail view? I have command filed in which showDeletebutton set to true.
I found how to do the confirmation for gridview, but how can I modify to match detail view?
Code:
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;";
}
}
}
}
Anybody?
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px"
.....
<asp:BoundField DataField="price" HeaderText="price" SortExpression="price" />
<asp:BoundField DataField="Quantity" HeaderText="Quantity"
SortExpression="Quantity" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="New" Text="New"></asp:LinkButton>
<asp:LinkButton ID="lnkDelete" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView
This can be done easily on the markup code. I simply added the js code to the onClientClick property of the delete button:
OnClientClick="return confirm('Are you sure you want to delete this record');"
Or if you want do this in the code behind:
protected void DetailsView1_DataBound(object sender, EventArgs e)
{
LinkButton bttn = (LinkButton)DetailsView1.FindControl("lnkDelete");
bttn.OnClientClick = "return confirm('Are you sure you want to delete this record!');";
}
I found the answer to my question.
My answer:
protected void DViewComputer_DataBound1(object sender, EventArgs e)
{
int noRow = DViewComputer.Rows.Count - 1;//get the no of record
if (noRow >0)
{
Button button = (Button)(DViewComputer.Rows[noRow].Cells[0].Controls[2]);
// Add delete confirmation
((System.Web.UI.WebControls.Button)(button)).OnClientClick = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
}
}
Anyways thanks for your help guys.
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.Attributes.Add("onclick","your javascript here");
}
Please see the below URL......
http://www.codeproject.com/Articles/32756/ASP-NET-GridView-delete-confirmation-using-asp-Com
This corrects the OP's solution. The code was translated from the code found here: http://forums.aspfree.com/net-development-11/confirm-button-when-deleting-detailsview-120113-2.html
protected void dvEvent_DataBound(object sender, EventArgs e)
{
int commandRowIndex = dvEvent.Rows.Count - 1;
if (commandRowIndex > 0)
{
DetailsViewRow commandRow = dvEvent.Rows[commandRowIndex];
DataControlFieldCell cell = (DataControlFieldCell)commandRow.Controls[0];
foreach (Control ctrl in cell.Controls)
{
if (ctrl is ImageButton)
{
ImageButton ibt = (ImageButton)ctrl;
if (ibt.CommandName == "Delete")
{
ibt.ToolTip = "Click here to Delete";
ibt.CommandName = "Delete";
ibt.Attributes["onClick"] = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
}
}
}
}
}
I want to delete record from GridView.Before to this ask for confirmation like "Are you sure to delete?"
I used command field in GridView,
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
I wrote a function in javascript
function confirm_Delete()
{
var r = confirm("Are you sure you want to Remove this Record!");
if (r == true)
{
alert("Record Deleted");
return true;
}
else
{
return false;
}
}
How I will call this on delete click.
Kindly suggest !
You can't achieve this using the command field, you have to make a template field:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbtnDelete" runat="server" CommandName="Delete" Text="Delete"
OnClientClick="javascript:return confirm('Are you sure you want to Remove this Record!');">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
It will behave the same way you are doing currently with the Command Field.
I would do the same as #Muhammad told you, and at the server side code for deleting I would also register an script for showing the "Record Deleted" message, as follows;
public void MethodForDeletingARecord()
{
ScriptManager.RegisterStartupScript(this.Page, base.GetType(), "RecordDeletedMessage", "javascript:alert('Record Deleted');", true);
}
I think you can achieve this for commandfield
Assuming it would be the first column, Found Here
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// reference the Delete LinkButton
LinkButton db = (LinkButton)e.Row.Cells[0].Controls[0];
db.OnClientClick = "javascript:return confirm('Are you certain you want to delete?');"
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
((LinkButton)e.Row.Cells[0].Controls[0]).Attributes.Add("onclick", "return Conformation();");
}
}