Check is dirty for the gridview in asp.net? - c#

I am developing a web application where I am using a GridView control to load data from the database.
I have a row that is loaded in editable mode. I have a save button which the user clicks after making the changes, and I want to check the IsDirty flag to stop the user from saving and notify them via an alert box. I'm using a Web User Control (ASCX) to load the GridView. How can I check dirty rows in the grid and stop the user from saving when user clicks the save button or logout button??
P.S. I am using a LoginView for the logout button.

You need to handle the OnRowUpdating event in your grid, for example:
<asp:GridView id="a" runat="server" OnRowUpdating="a_rowUpdating" ... />
In code behind:
protected void a_rowUpdating (object sender, GridViewUpdateEventArgs e)
{
//Add logic appropriately to know whether you should allow the update or not.
//If you shouldn't, just set e.Cancel=true as below:
e.Cancel=true;//will stop from updating.
}
You have access to the Old and New values in the GridViewUpdateEventArgs object. For more details and sample code, check here.

I use a simple JS method to check for a variety of changes in ASP.net pages. I added it to a JS filer called CheckDirty.js and added a link to it on the page, in the file is this code:
var checkDirty = true;
var form_clean;
//this should be called when the save button is clicked, but prior to the page post
function onSave() {
checkDirty = false;
}
// serialize clean form
$(function () {
form_clean = $("form").serialize();
});
window.onbeforeunload = function (e) {
if (checkDirty) {
var form_dirty = $("form").serialize();
if (form_clean != form_dirty) {
return 'Your changes will be lost';
}
}
};
This will also work for changes to a gridview and will alert the user. I find this method best because it works with everything and I don't need to keep writing different methods for different controls.

Related

How to hide a control and prevent control from loading data

I have a page that have the following code for a custom control:
<SiteControls:Announcements runat="server" id="UserAnnouncements" />
Let's also say I have a GridView control, just so I can cover multiple scenarios. I need to check if the user has permission to view this control by checking the Boolean:
PermissionsManagement.DoesUserHavePermission(userId, permissionId)
Which is defined as:
public static class PermissionsManagement
{
public static bool DoesUserHavePermission(int userAccountId, int permissionId)
{
// Code Goes Here
}
}
If the user doesn't have permission, DoesUserHavePermission will return false. I have the ASP.NET WebForms page laid out as if the user has full control (meaning I have all the controls on the page and want to remove them if they don't have permission vs adding every single control to the page).
I can set the control's visibility to false on Page_Load function if the user doesn't have permission, but that doesn't stop my control from loading or in the case of a GridView from loading its data. How do I stop a control (User control or standard control) from loading any data if the user doesn't have permission to use (view) the control? I have tried the following inline code which doesn't work:
<% if(PermissionsManagement.DoesUserHavePermission(1, 1))
{ %>
<SiteControls:Announcements runat="server" id="UserAnnouncements" />
<% } %>
But that doesn't work as the control Page_Load still fires for the control and I assume any other control will load data if it is data-bound or acts similar to my control.
Without knowing much of your code, it is a little difficult to figure out the exact answer. However, as much as I understood your question, here's my answer.
Loading data for Announcements or GridView should still be in your control. I would expose a method in Announcements control that actually loads data for it. For the GridView you should simply defer the binding of DataSource until the permission check is performed. Of course these things need to be done in addition to hiding (setting visibility) of these controls.
See the code below, not complete, but enough to express an idea:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Check permissions here
if (allowed)
{
// For custom/user control
UserAnnouncements.GetAnnouncements();
// For grid view
GridView1.DataSource = GetGridviewData(); // GetGridviewData would return DataSet or anything valid.
GridView1.DataBind();
}
else
{
// Hide the controls
}
}
}

ASP.Net C# - Redirect to a page

I've got a 'menu' within a Master page which includes a number of image buttons with click events.
Within each click event, I want to redirect the user to a specific (Child) page. However, if the user is already on the correct (Child) page, I don't want to refresh the page and lose the entered data.
In the example below, I want to redirect the user to browse.aspx however, if the user is already on browse.aspx, I don't want to refresh it.
Is there a better way to do this than the following?
protected void ibtnBrowse_Click(object sender, ImageClickEventArgs e)
{
if (!Request.Url.Segments[1].ToString().Equals("browse.aspx"))
{
Response.Redirect("~/browse.aspx");
}
}
How about disabling the Image button on the page?
e.g.
When you are on browse.aspx, in code behind browse.aspx.cs you can disable the button.
ImageButton iBtn = (ImageButton)Page.Master.FindControl("ibtnBrowse");
iBtn.Enabled = false;
By having server side click events the page will always "refresh" when clicking on these buttons. However, if you are simply looking to avoid doing an unnecessary redirect in your code you can use:
HttpContext.Current.Request.Url.AbsoluteUri
or
HttpContext.Current.Request.Url.AbsolutePath
If you decide to use javascript to switch between pages you can use location:
location.replace("http://www.w3schools.com");
location.assign("http://www.w3schools.com");

Event before redirect to another page

I've just developed a new GridView MultiFilter control ( CompositeControl ) that works like the image below:
I use ViewState for my control's properties so it keeps all values after postback. I want to save my control properties to a Session before redirect so I can load properties back to my control when my page loads again.
Does anyone have any suggestions about how this can be accomplished?
You have to do 2 things in this list page:
(1)Page load
(2)Search click
And 1 thing in detail (redirected) page:
(3)Pass some query string while back to list page
(1)while page load decide to load normal or searched (back from detail page) data
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["back"] != null)
bindDataFirst();
// same data load logic as present
else
bindDataForBack();
// you come back from detail page hence bind search & grid data
}
private void bindDataForBack()
{
strName = Session["SearchName"] == null ? "" : Session["SearchName"].ToString();
// check session search conditions & data and bind
//also bind grid by respective search parameters & search options (top side)
(2)search click store search data into session
public void btnSearch_Click(object sender, System.EventArgs e)
{
Session["SearchName"] = strName;// store search data into session variables
//bind grid by respective search parameters
(3)in redirected (detail) page set back button like:
public void btnBack_Click(object sender, System.EventArgs e)
{
Response.Redirect("ListPage.aspx?back=1");
I hope this may helps you. I suggest to implement this with one textbox & grid and then try with your present scenario.
Please mark this answer useful if this solve your problem.
You can assign data to Session the pretty much the same way you assign to ViewState.
It's a key value dictionary just like ViewState.
Ex:
Session["someKey"] = "An arbitrary value";
If you can redirect to another page using form submit then You can post your form to the required page using action attribute of your page. This way values of all controls will be available in the Request["KEY NAME HERE"]
<form action="anotherpage.aspx" id="frmData">
<!-- YOUR CONTROLS HERE -->
<input type="submit" value="Submit" />
</fomr>
you can also submit your form using JS
$("#frmData").submit();

how to get the return value from a JS dialog box in asp.net without tying it to a button

How can one display a confirmation box & get the return value in C# code in ASP.NET without tying it to a button? I need to display the confirmation box from inside the event handler of a button if a certain condition is filled.
Situation:
protected void okBtn_Click(object sender, EventArgs e)
{
if (blah)
{
bool answer = DisplayConfirmationBox();
}
}
Displaying it using JS is not really an issue, but getting the return value from it is.
Javascript is executed on the client, ASP.NET/C# on the server.
To get the value from your JS Dialog Box to the server, so you can work with it in your server side code, you have to either store it in a (Hidden) Text Field and perform a PostBack or do an asynchronous AJAX request.
For the first method see the HiddenField server control and to trigger a PostBack from JS you can use
__doPostBack(control, arg);

Testing if a button has been clicked or not

I have an asp.net page which loads and writes values from a record to the controls on the page.
There is a link to another page and a save button.
If the user clicks save, fine, the changes are saved and they can navigate to wherever.
If they dont click save and click the link, any changes are lost.
Is there a way to check if the save has been clicked while the user has that page loaded?
I'm thinking along the lines of an OnClick Javascript function for the link such as -below, I'm not sure though how to test for the save button being clicked - can anyone point me in the right direction?
function handleHyperLinkClick(hyperlink)
{
confirm("You have not clicked save, any changes will be lost - click cancel then save your changes or ok to continue");
}
Add a bool variable, that is default false, set to true if the button has been clicked. Then check the value if user leaves the page.
You can do using hidden field. when user click on save button then set hidden field value.
You have to keep a temporary variable in javascript like state;
`
var state = 0;
//your function calls here
function yourFunction()
{
//// your coding
state =1;
//// your coding
}
`
In this case, you have to submit the value or navigate to other page when state=1, otherwise you shouldnt. This flag to be checked whilst clicking link (if its navigating via function) or onBeforeUnload event for page.
Please correct me know if you are looking for something other.
You can attach some value to a variable when the button is clicked. Then when the user tries to navigate, check whether that variable has that value. If so, it has been clicked, else not:
button = document.getElementById("button");
button.onclick = function() { clicked = true; }
document.getElementById("link").onclick = function() { if (!clicked) { alert("Sure?"); }
Assuming you are using ASP.NET server buttons like this:
<asp:Button runat="server" id="someButtonId" Click="someClickHandler" Text="Continue" />
If I were you, I would use jQuery to dynamically bind the click event of the button like this:
$(document).ready(function() {
$("input[type=button][id$=someButtonId]").on("click", function(e) {
if(!confirm("You have not clicked save, any changes will be lost - click cancel then save your changes or ok to continue"))
{
e.preventDefault()
}
});
});
Hope this helps.

Categories