I have a asp gridview. On row databound I add onclick event to view item details. I have also delete button. The problem is When I click item delete, it deletes item but also redirect to item preview page. It should not do a postback and redirect
here is my code
protected void Grid_DataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes["onClick"] = String.Format("location.href='" + "/Url/page.aspx?id=" + "{0}", DataBinder.Eval(e.Row.DataItem, "Id") + "'");
}
delete button
public void GvDeleteHabit(object source, CommandEventArgs e)
{
int id= Convert.ToInt32(e.CommandName);
Delete(id);
}
<asp:LinkButton OnCommand="Delete" title="Delete" OnClientClick="javascript:return confirm('Do you want to delete?')"
CommandName='<%# Eval("Id")%>' runat="server" ID="BtnDelete"></asp:LinkButton>
on client side I have confirm message. So what I'm trying to achieve is when user click delete button and Yes, I need to remove onclick event from row and delete item.
if user click No stop page from loading. so user can click somewhere on row and view details of item
Try by removing javascript: from OnClientClick. It's only needed if javascript is used in the href attribute.
The problem you're running into is that even when you click "Delete" is still registers as a click event on the row, which in turn fires off the redirect. You should put your redirect into a function, and pass in the source of the click event. If the source is your button, exit the function.
onRowClick = function(source){
if (source.element.type == "button") // this may not be correct, but you get the point
return confirm('Are you sure you want to delete this item');
//do your redirect here
}
e.Row.Attributes["onclick"] = "onRowClick(this);";
AND in your HTML markup:
<asp:LinkButton OnCommand="Delete" title="Delete" OnClientClick="javascript:return onRowClick(this);"
CommandName='<%# Eval("Id")%>' runat="server" ID="BtnDelete"></asp:LinkButton>
Since you have onclick handler on row also, you have to basically stop the event propagation on delete button click, try this it will solve the problem.
ASPX Change
<asp:LinkButton OnCommand="Delete" title="Delete" OnClientClick="javascript:return confrimDelete(e);"
CommandName='<%# Eval("Id")%>' runat="server" ID="BtnDelete"></asp:LinkButton>
Add this method in any of your js file or on the page
function confirmDelete(){
var event = e || window.event;
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
return confirm('Do you want to delete?');
}
Related
I am showing my data in data list using grid view each grid view includes a button click how how can I store a particular button click value in a session and redirect the value to next page
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Button2")
{
Response.Redirect("movers_packers_profile.aspx?sp_id=" + e.CommandArgument.ToString());
}
}
Please check whether your button is set like this
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Button2" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "sp_id")%>' />
While, I want to trigger btnSearchSuiteGroup_Click event when pressing "enter" on txtSuiteGroupName which described in aspx, code below:
<asp:TextBox ID="txtSuiteGroupName" runat="server" clientidmode="Static" CssClass="DD" onkeypress="return searchKeyPress(event)"></asp:TextBox>
<asp:Button ID="btnSearchSuiteGroup" runat="server" Text="Search" CssClass="DD" Width="64px" onclick="btnSearchSuiteGroup_Click" />
<script type="text/javascript">
function searchKeyPress(e) {
// look for window.event in case event isn't passed in
if (typeof e == 'undefined' && window.event) { e = window.event; }
if (e.keyCode == 13) {
document.getElementById('<%=btnSearchSuiteGroup.ClientID%>').click();
}
}
</script>
While, the btnSearchSuiteGroup_Click is defined in the source cs file:
protected void btnSearchSuiteGroup_Click(object sender, EventArgs e)
{
this.LinqDataSource1.WhereParameters["SuiteGroupName"].DefaultValue = this.txtSuiteGroupName.Text;
this.GridView1.DataBind();
if (GridView1.Rows.Count == 0)
Response.Write("<script language='javascript'>window.alert('No record found!')</script>");
}
When I browse the website, the keypress on the textbox cannot initiate the button click event, anything wrong in the code?
If you use Panel you would not need to use any javascript function. You can specify default button Id for panel like below
<asp:Panel runat="server" DefaultButton="btnSearchSuiteGroup">
<asp:TextBox ID="txtSuiteGroupName" runat="server" clientidmode="Static" CssClass="DD">
</asp:TextBox>
<asp:Button ID="btnSearchSuiteGroup" runat="server" Text="Search" CssClass="DD" Width="64px" onclick="btnSearchSuiteGroup_Click" />
</asp:Button>
</asp:Panel>
OfCourse you can have Multiple panels on single page for assigning different default buttons for separate panels!
For More On Panel.DefaultButton Property
I suggest the following method:
1. Create a function 'ButtonClick' and put all the code in 'btnSearchSuiteGroup_Click' function into it.
2. Add 'onkeypress' event for the textbox 'txtSuiteGroupName' by looking at this thread
3. Whenever the above event is fired, see if the entered key is 'Enter'.
4. If the key is 'Enter' key, call the function 'ButtonClick'.
In my gridview, I have included a column containing a LinkButton that allows you to delete the record on the same row where the LinkButton is :
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkDeleteTxn" Text="Delete" runat="server" CommandArgument='<%# Eval("TxnID") %>' OnClick="deleteTxn"
OnClientClick="return confirm('!!--WARNING--!! You are about to delete the transaction. Performing this action will permanently remove the transaction and all its details from the database. Proceed?');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
This LinkButton includes showing a pop-up window asking if the user really wants to delete the record. Now, for my RowDataBound event, I set it so that whenever the Status of the Record is "Approved", the Delete LinkButton is disabled:
string recStatus = Convert.ToString(DataBinder.Eval(e.Row.DataItem,"StatusDesc"));
if (recStatus == "Approved")
{
hlTxnEdit.Enabled = false;
lnkTxnDelete.Enabled = false;
}
else
{
hlTxnEdit.Enabled = true;
lnkTxnDelete.Enabled = true;
//lnkTxnDelete.Attributes.Add("OnClientClick", "return confirm('!!--WARNING--!! You are about to delete the transaction. Performing this action will permanently remove the transaction and all its details from the database. Proceed?')");
}
the problem is, when the user clicks on the disabled LinkButton, the confirmation pop-up still displays, when it should not, because the LinkButton is disabled. Makes a bit of sense, because the Attribute where the pop-up window is set is on the OnClientClick attribute. How do I make the pop-up window not show up? I tried adding the OnClientClick attribute in the code behind, but it doesn't work. The LinkButton proceeds straight on deleting the record.
if (recStatus == "Approved")
{
hlTxnEdit.Enabled = false;
lnkTxnDelete.onClientClick = null;//
}
else
{
hlTxnEdit.Enabled = true;
lnkTxnDelete.Enabled = true;
//lnkTxnDelete.Attributes.Add("OnClientClick", "return confirm('!!--WARNING--!! You are about to delete the transaction. Performing this action will permanently remove the transaction and all its details from the database. Proceed?')");
}
Make change in your aspx as below...
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkDeleteTxn" Text="Delete" runat="server" CommandArgument='<%# Eval("TxnID") %>' OnClick="deleteTxn"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Add your confirmation pop-up from the code behind like this.
string recStatus = Convert.ToString(DataBinder.Eval(e.Row.DataItem,"StatusDesc"));
if (recStatus == "Approved")
{
hlTxnEdit.Enabled = false;
lnkTxnDelete.Enabled = false;
lnkTxnDelete.Attributes.Add("onclick", "return false;");
}
else
{
hlTxnEdit.Enabled = true;
lnkTxnDelete.Enabled = true;
lnkTxnDelete.Attributes.Add("onclick", "return confirm('!!--WARNING--!! You are about to delete the transaction. Performing this action will permanently remove the transaction and all its details from the database. Proceed?')");
}
Rather than defining the OnClientClick attribute in template field.
Add the OnClientClick attribute on your RowDataBound event when status is Approved.
lnkButton.Attributes.Add("OnClientClick","Javascript");
You can fix the issue in these steps.
Remove the OnClientClick from Declaration html.
On GridView OnDataRowBound event handler in the code behind add this OnClientClick
lnkTxnDelete.Attributes.Add("OnClientClick", "return confirm('!!--WARNING--!! You are about to delete the transaction. Performing this action will permanently remove the transaction and all its details from the database. Proceed?')");
Make sure you are adding this code only when recStatus <> "Approved".
I have an asp.net page and on it there are a number of controls, including:
A textbox with autopostback = true and the server side textchanged event implemented
A button with the server side click event implemented
The textbox performs the postback as soon as the user leaves the control (ie, focus is lost). The problem is that if the user happens to change the value and then press the button without leaving the textbox, then on button click the textbox will perform the postback but the button click will be lost.
How can i force both the textbox and the button events to fire consecutively in such cases?
Thanks
Try:
ASPX:
<asp:TextBox ID="TextBox1" clientidmode="Static" runat="server" onkeypress="return EnterEvent(event)"></asp:TextBox>
<asp:Button ID="Button1" runat="server" style="display:none" Text="Button" />
JS:
function EnterEvent(e) {
if (e.keyCode == 13) {
__doPostBack('<%=Button1.UniqueId%>', "");
}
}
CS:
protected void Button1_Click1(object sender, EventArgs e)
{
}
You can delay postback from textbox and cancel it in case of button click. To do this add code below to Page_PreRender method:
protected void Page_PreRender(object sender, EventArgs e)
{
Button1.OnClientClick = string.Format("if(window.{0}Timeout){{ clearTimeout(window.{0}Timeout); }}",
TextBox1.ClientID);
TextBox1.Attributes["onChange"] = string.Format("javascript:window.{0}Timeout = setTimeout(\"{1}\", 500); return;",
TextBox1.ClientID,
ClientScript.GetPostBackEventReference(TextBox1, ""));
}
This may be a silly question but i'm a beginer here..
I created a form in asp.net and it's all fields are validated using validation controls on clicking an image button.It is working properly.After that i add an event to the button.This is the code of that button.
<asp:ImageButton ID="Submit" runat="server" OnClick="submit_Clicked" ValidationGroup="AddSchoolValidationGroup" CausesValidation="true" ImageUrl="~/Styles/images/submit-btn.png" OnClientClick="submitClicked" />
The purpose of that event is for submitting all the values in the form to database.Here my problem is,After adding the onClick event to button, validation has not taken place.And i want these onClick event to raise only when the form is validated successfully.Can any one guide me ..Thanks in Advance.
make sure that you are using the same validation group for all the validation controls.
in addition you can use OnClientClick event to call validation.
<asp:ImageButton ID="Submit" runat="server" OnClick="submit_Clicked" ValidationGroup="AddSchoolValidationGroup" CausesValidation="true" ImageUrl="~/Styles/images/submit-btn.png" OnClientClick="return Page_ClientValidate('AddSchoolValidationGroup');" />
You need to validate the page before submitting. Please add attribute for button.
protected void Page_Load(object sender, EventArgs e)
{
Submit.Attributes.Add("onclick", "javascript:if(Page_ClientValidate('AddSchoolValidationGroup')){return true;}else{return false;}");
}
Since you have a method "submitClicked" in onclient click, you can call the same inside Page_ClientValidate and remove the existing "OnClientClick" property.
protected void Page_Load(object sender, EventArgs e)
{
Submit.Attributes.Add("onclick", "javascript:if(Page_ClientValidate('AddSchoolValidationGroup')){submitClicked(); return true;}else{return false;}");
}
You can use javascript function
function validateForm() {
if (document.getElementById('txtName').value == '')
{
ValidatorEnable(document.getElementById("rfvName"), true) // rfvName is id of validator
return false; }
}
and call that function on client click of image button
<asp:ImageButton ID="Submit" runat="server" OnClientClick="validateForm();" OnClick="submit_Clicked" ValidationGroup="AddSchoolValidationGroup" CausesValidation="true" ImageUrl="~/Styles/images/submit-btn.png" />
Replace OnClientClick="submitClicked" with OnClientClick="return submitClicked();"
function submitClicked()
{
if (document.getElementById('txtname') != '') {
return true;
}
else {
alert('Please Enter Name');
return false;
}
}
So until all the validations are validated, the Server side event will not be called.