disable OnClientClick when LinkButton is disabled - c#

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".

Related

View button with if else statement

I have a gridview and I want to add a button 'VIEW' which redirects to the (Customers.aspx?CustomerID=) page. Every customer has a ID and each ID is associated with a report. I don't want the ID to show up in my gridview and I want it to be hidden.
Also, I want this button to show up only if the USER is an "Admin" or a "Salesperson" category. I s there a way i can bind my CustomerID to a UserCategory to generate reports for each ID separately.
I tried looking at some other posts as well but my button doesn't redirect for some reason.
Can someone please help me figure out what i am doing wrong here or if i am missing something. Any help will be greatly appreciated.
Thank you.
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="btnView" runat="server" CausesValidation="false" CommandName="Select" Text="VIEW" />
</ItemTemplate>
<ControlStyle CssClass="button" />
</asp:TemplateField>
protected void btnView(object sender, EventArgs e)
{
Button button = (Button)sender;
GridViewRow row = (GridViewRow)button.NamingContainer;
Label lblCustomerID = (Label)row.FindControl("lblCustomerID");
txtHFUserCategory.Value = Session["UserCategoryPC"].ToString();
String strUserCat = MTProcs.GetSingleDatabaseResult("SELECT tblUsers.UserCategoryID FROM tblUsers WHERE UserID = " + txtHFUserID.Value);
if (strUserCat == "4" || strUserCat == "12")
{
ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", "window.open(Customers.aspx?CustomerID=" + lblLeadID.Text + "');", true);
}
}
Hi you can do it with simply adding visible property in your button
like
<asp:button ID="yourBtnID" runat="server" Text="WotEver" visible='<%# Convert.toInt(Eval("admin"))==1 && Convert.toInt(Eval("SALESPERSON"))==1 %>'/>

Disabling a postback of a dynamic imageButton

I have a table in an update panel. This table gets filled form the code behind and there is also a button added. This button triggers a Javascript. Because this button triggers a Javascript I don't need the button to do a postback. Is there a way to disable this postback?
This is the code I use to set the imagebutton in a table cell for each row.
ImageButton ibtnTableOneNewComment = new ImageButton();
ibtnTableOneNewComment.ImageUrl = "~/img/Pencil.png";
ibtnTableOneNewComment.OnClientClick = "setDiscription('test', 'testy')";
tabCell.Controls.Add(ibtnTableOneNewComment);
The table headers get set in the asp, the rest from the code behind.
<asp:UpdatePanel runat="server" ID="up_tableMain" UpdateMode="Conditional">
<ContentTemplate>
<asp:Table runat="server" ID="tbl_main">
...Headers...
</asp:Table>
</ContentTemplate>
</asp:UpdatePanel>
Put return false; in your OnClientClick
You have to add return false; in the OnClientClick event of the button. This will block it to send any Postback request to Server:
ImageButton ibtnTableOneNewComment = new ImageButton();
ibtnTableOneNewComment.ImageUrl = "~/img/Pencil.png";
ibtnTableOneNewComment.OnClientClick = "setDiscription('test', 'testy'); return false;";
tabCell.Controls.Add(ibtnTableOneNewComment);

Get record id using GridView Linkbutton on one page and get on another page in ASP.NET using C#

How do I submit the id from one page to another page in ASP.NET using C#? I have a GridView control and each record contains a link button:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbtn_naatscat" runat="server" Text="arshad" CommandName="view_user_naats_gv" Font-Underline="false" />
</ItemTemplate>
</asp:TemplateField>
I've bound the id to link button:
if (e.Row.RowType == DataControlRowType.DataRow)
{
((LinkButton)e.Row.FindControl("lbtn_naatscat")).CommandArgument
= DataBinder.Eval(e.Row.DataItem, "cate_id").ToString();
((LinkButton)e.Row.FindControl("lbtn_naatscat")).Text
= DataBinder.Eval(e.Row.DataItem, "title").ToString();
}
now I want to pass this id to another page when user click to this link button.
You can handle the LinkButton's Command event and use the CommandArgument:
void LinkButton_Command(Object sender, CommandEventArgs e)
{
if(e.CommandName == "view_user_naats_gv")
{
Resonse.Redirect("UserNaats.aspx?catID=" + e.CommandArgument.ToString());
}
}
You can create a Session for this purpose.
Do as follows:
Session["Id"]=e.CommandArgument.ToString() //Id you want to pass to next page
In this way your Session variable will get created. And you will be able to access it on the next page.
While retrieving it on next page:
Id=Session["Id"]
Other Alternatives:
View state
Control state
Hidden fields
Cookies
Query strings
Application state
Session state
Profile Properties
State management Techniques in ASP.NET:
http://msdn.microsoft.com/en-us/library/75x4ha6s%28v=vs.100%29.aspx
Hope its helpful.
Store it in a hidden field, and access it on the next page in the code behind file.
Here is another SO post with
Another example of passing hidden field in ASP
Best of luck!
I would use a HyperLinkField field like so
<asp:HyperLinkField DataNavigateUrlFields="Database ID Field"
DataNavigateUrlFormatString="~/PageName.aspx?ID={0}"
DataTextField="Database ID Field" HeaderText="ID" />
And then on the page that you're redirecting to, you would check the query string for ID
string id = Request.QueryString["ID"]
Set the PostBackUrl and CommandArgument properties of the LinkButton in your source page like so:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbtn_naatscat" runat="server" Text="arshad" CommandName="view_user_naats_gv" Font-Underline="false" PostBackUrl="~/YourPage.aspx" CommandArgument='<%# Eval("submitid")%>' />
</ItemTemplate>
</asp:TemplateField>
Then on your page that is being submitted to you can place the following directive to the DestinationPage.aspx page:
<%# PreviousPageType VirtualPath="~/SourcePage.aspx" %>
I don't know what type of container the <ItemTemplate> tag is from (ListView?). However you can find the control in the DestinationPage.aspx page like so:
if (Page.PreviousPage != null && Page.PreviousPage.IsCrossPagePostback) {
// if you use the PreviousPageDirective you should be able to access the ListView
// property directly
// var listView = Page.PreviousPage.MyListView;
var listView = Page.PreviousPage.FindControl("MyListView") as ListView;
var linkButton = listView.FindControl("lbtn_naatscat") as LinkButton;
var submitId = linkButton.CommandArgument;
}
Using Row_Command event you can send it next page using query string.
protected void gvDeals_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName.Equals("MyCommand")
{
string value=calculate();
Response.Redirect("~/MyPage.aspx?item=" + value);
}
}
I think it would make more sense to use a hyperlink in your GridView.
For example:
<ItemTemplate>
<asp:HyperLink ID="link_naatscat" runat="Server"
Text="arshad"
ToolTip="arshad"
NavigateUrl=<%#"~/YourPage.aspx?id=" + Eval("submitid")%>>
</asp:HyperLink>
</ItemTemplate>
Send the id this way
Response.Redirect("/yourpage.aspx?" + id);
And get it this way
String s = "";
foreach (String item in Request.QueryString.Keys)
{
s = Request.QueryString[item];
}
if (s != "")
{
id = Int32.Parse(s);
}

How to remove row on click on confirm message true?

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?');
}

disable delete button if value in database table's--> column is true or checked

Ok... I have a database table called employees..
This has columns called ID, Name, datejoined and Cannotbedeleted (check boxes)...
Now i want to add a delete column which deletes the rows when clicked.
But there are some entries which cannot be deleted if the Cannotbedeleted field is true (checked)... so the delete button should be invisible for these rows.
Please tell me a way of how to do this...
<asp:CheckBoxField DataField="CannotBeDeleted" HeaderText="CannotBeDeleted"
SortExpression="CannotBeDeleted" />
<asp:BoundField DataField="TimeAdded" HeaderText="TimeAdded"
SortExpression="TimeAdded" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I also tried using in delete template field...
' >
But i did not know what to do in code behind??
protected bool GetShowDeleteButton()
{
}
The solution is below.... but is there a way i can refresh the page once i click the delete button in the gridview....
Try looping through the rows in GridView_DataBound, and hide the button for each row that has the checkbox checked.
protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach(GridViewRow myRow in GridView1.Rows)
{
//Find the checkbox
CheckBox ckbox1 = (CheckBox)myRow.FindControl("nameOfCheckBox");
if(ckbox1.Checked)
{
//Find the Delete linkbutton and hide it
LinkButton deleteButton = (LinkButton)myRow.FindControl("nameOfDeleteLinkButton");
deleteButton.Visible = false;
}
}
}
Now, here's the difference you need:
Implement the CheckBox column as a TemplateField with a CheckBox in it. You can bind the CheckBox to the data from your datasource.
Do it like this:
if($row['cannotbedeleted'] == true) {
$buttonDisplay = 'none';
}
echo "<button onclick='delete();' style='display: $buttonDisplay;'>Delete</button>";
Well that would be the solution in PHP but if the style of the button has "display: none;" in it the button will be hidden. :) HTH

Categories

Resources