How to stop an Loading function on button click? - asp.net

I have a problem, I have to stop one Loading class on button click. I already checked some forums related to this. But didn't find an exact solution.
For example:
Public Sub LoadDropDown()
Dim it As Integer
For it = 0 To 1000000
DropDownList1.Items.Add(it)
Next
End Sub
I have to load the DropDown on Load button click and I have to cancel that on cancel button click.

Since populating the control happens on the server, I can't imagine way to interrupt your method from the client. The whole control is being populated, rendered, and only then sent to the client. You might interrupt the callback using ajax, but then the control wouldn't be returned at all.
An alternative could be to load the contents in chunks with ajax and append them to the control on the client-side.

There is no formal way to do what you're asking, but you should be able to achieve the same result if you refactor your code. If certain content shouldn't be loaded for certain users, do that logic in your code behind before it renders to the page.

Per your response to the other answers...
You could consider doing multiple my_ddl.items.add() calls on a timer. Would involve multiple, separate postbacks / ajax calls. For example:
1) add records for 2 seconds (instead of a fixed number of records at a time)
2) check for session("continue") = "true"
3) add more records for 2 more seconds
4) check session("continue")
...
At some point, user clicks cancel, which assigns "false" to session("continue"). Next time your loop checks session("continue"), it will see that it's false and exit.
This would give you a partially-loaded data control. You might want other code to wipe-out the partial update.

I think you could accomplish this with a Session Variable. Forgive me, but I'll have to provide the example in C#, but I'm sure you can get the general idea of this.
private bool CancelRequested
{
get
{
if (Session["CancelRequested"] == null)
return false;
else
return (bool)Session["CancelRequested"];
}
set
{
Session["CancelRequested"] = value;
}
}
public void LoadDropDown()
{
for (int it = 0; it <= 1000000; it++)
{
if (CancelRequested)
{
CancelRequested = false;
break;
}
//Your logic here
}
}
protected void btnCancelRequest_Click(object sender, EventArgs e)
{
CancelRequested = true;
}
The idea here is that the inital loop checks a Session variable to see if it should continue or break out of the loop. If you have a button on the page that will allow the user to set this Session variable to "true", they can essential communicate to the inital request and cause it to break out of the loop. I'm not sure if this would fully accomplish what you're looking to achieve, but hopefully it helps.

Related

why the size of List in not incrementing

I create dynamically checkboxes all of them with assigned checkedChanged event, which on postback I recreate and everything is working except one thing;
I should save the value of checked checkboxes in a List . But it seems that on each postBack event (every time I check a checkbox) the elements of the list are lost although myche is a global variable of type List ;
lblProba.Text +="in if clause; element count="+ myche.Count.ToString();
gives me 1 every time I check a checkbox
protected void checkChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
myche.Add(chk.InputAttributes["value"].ToString());
lblProba.Text +="in if clause; element count="+ myche.Count.ToString();
}
else
{
lblProba.Text += "enering else;element count:"+myche.Count.ToString();
}
lblProba.Text += "Final length" + myche.Count.ToString();
for (int t = 0; t < myche.Count; t++)
{
Session["chk"]+= myche[t];
}
}
In a web application you can think of every postback as leading to a completely new start of your application. It doesn't remember any state, all the objects are being instantiated as if it's the first time your application is running.
ASP.NET tries to hide this fact by employing things like ViewState etc., but nevertheless your server-side objects don't live beyond a single request/response cycle.
To carry state through multiple requests you could store intermediate values in the Session variable.
You need to check on the lifecycle of ASP.NET pages. Each time you call a page, ASP.NET creates a new instance of the page, loads it with any Viewstate data (if this is a postback) and passes control to your Load event. Once the page sends the response to the browser, the instance is destroyed.
ASP.NET manages ViewState for the statically created controls automatically. You will have to ensure that any data required to rebuild and populate your dynamic controls is saved in the ViewState and used to rebuild them in your Loaded event.
You should store your list e.g. in Session object to avoid losing it on every postback.

Linq data not updating form after postback

In my application, I have a form that users fill out, then gets approved by a manager. I have various types of forms that all use the same process, so the approval buttons are all done via a user control (which includes the functionality to update the data in the database and call the postback).
However, once I click on the "Approve" button (which is in the user control), the form information doesn't update (it still says "unapproved"). A postback is definitely happening, but not sure why the page isn't updating properly.
I can confirm that the change are being made - when I manually reload the page, it gets updated - but not on the post back.
What am I missing here?
My page:
protected void Page_Load(object sender, EventArgs e)
{
int ID;
// ensure that there's an ID set in the query string
if (Int32.TryParse(Request.QueryString["ID"], out ID))
PopulatePage(ID);
else
Response.Redirect("~/Default.aspx");
}
}
protected void PopulatePage(int ID)
{
using (WOLinqClassesDataContext db = new WOLinqClassesDataContext())
{
lblStatus.Text = wo.Workorder.status;
....
}
}
I think that the Page_Load happens before the code in the submit button. To check this just use a couple of breakpoints. So the page loads the old data since the new data are not saved yet.
You should call a method to load the data inside the OnClick method of the Approve button.
After you've submitted the changes to the database, try running db.Refresh(RefreshMode.OverwriteCurrentValues) to force the changes to be reloaded into the data context.

showEvent() called more than once - Intentional?

What I want to do is display a set of pages setting up a test. Once all the details are correct the user presses Commit and the next wizard page is displayed that I want to immediately run a series of tests in. Displaying those to the user and once complete the user can then click Next.
I know to disable Next is simply a case of returning false on isComplete() and that is implemented okay. So, I want to use the function that is called just after the widget is displayed and so I used showEvent() which was indicated to me as the function to use.
At the moment my test is just displaying a progress bar as a test hence using a timer.
void RunTestWizardPage::showEvent(QShowEvent *event)
{
ui->statusEdit->setText("Running Tests");
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(100);
}
void RunTestWizardPage::update()
{
static int i = 10;
ui->statusEdit->append("Running Tests...");
ui->testProgress->setValue(i++);
if(i == 100)
{
i = 0;
timer->stop();
complete = true;
emit completeChanged();
}
}
However this function appears to be called twice (and I think before the widget display although that may be a trick of my debugging) and as such it causes issues with the timer I think as the timer never ends. I did read in the docs about spontaneous events but from what I can see both calls to the function are not spontaneous.
Is it being called twice intentional and if so how do I stop it or is there another function to use?
Thanks!
There is QWizardPage::initializePage() which is called just before showing the page.

GridView_RowCommand event fired again on page refresh

I have implement GridView Row Editing feature in my .net application using <asp:CommandField.
I clicked on Update button to save the record after editing the row.Now if i refresh the page or press F5 GridView_RowCommand fired again.
How can we avoid this.Is there any mechanism to identify when user press F5 OR refresh the page.Is there any method in client side or in server side.
Not exactly the best "technical" solution to your problem but you could always just do a Response.Redirect(Request.RawUrl) once you have finished doing anything you need to do in your RowCommand
Like I said, it's not the best "technical" solution but it is a solution
Dave
One method of capturing this is to maintain a session variable that is related to the page in question. In the session variable you would keep some kind of state enumeration, key or string that would determine the last action taken. You could even use a simple incremented counter, and if you ever received a postedback counter that was equal to the session variable it would indicate a page refresh rather than a new action.
Session["LastInsertedItem"] = null;
MyCustomObjType myCustomObject;
protected void Page_Load(object sender, EventArgs e)
{
myCustomObject = Session["LastInsertedItem"] as MyCustomObjType;
}
void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
If(myCustomObject == null || //!(compare your value with myCustomObject.field) )
{
// do your operations and save the values to myCustomObject and save that object back to Session.
}
else
{
// It is refreshed or same data is being insterted - don't know if second option is possible in your case.
}
}

Asp.Net GridView EditIndex race condition?

This is a bit of a hypothetical question that has sent me off down the garden path... Say I have a gridview that I'd like to edit... given a method that binds the data..
private void BindGridFirst() {
var data = new List<string>() {
"A","B","C","D","E","F"
};
gridView.DataSource = data;
gridView.DataBind();
}
Now presume that I'm looking at this page, and another user has come along and made some changes to the underlying data, and I now go and click the edit button to edit D...
The edit method is pretty straight forward:
protected void RowEdit(object sender, GridViewEditEventArgs e) {
gridView.EditIndex = e.NewEditIndex;
BindGridSecond();
}
Edit: I feel compelled to point out, that this method is used in pretty much all the online examples, including ones from Microsoft.
This BindGridSecond() method looks like so:
private void BindGridSecond() {
var data = new List<string>() {
"A", "AA", "B","C","D","E","F"
};
gridView.DataSource = data;
gridView.DataBind();
}
It's exactly the same, but the data is now changed. Once the UI updates, the user is now in edit mode against row C.
Not what the user expected or wanted. How should this scenario be handled to avoid such an issue?
Personally, I use the DataKeyNames property and the SelectedDataKey on the GridView, so that I can easily obtain the primary key of the row the user wants, rather than relying on the index of the grid.
By using the primary key, you don't have any issues with new items being added to the collection, such as in your example. Plus, using the primary key makes it easier to deal with paging on the grid, as you don't have to take the page number and index into account.
Imho there are two options:
You could cache the Data you want to bind to the Grid in a Session for example. So you are able to check for changes before you call the BindGridSecond-Method and alert the user if any changes have been made while he was browsing the Page.
In option 2 you would again cache the Data you were binding in the BindGridFirst-Method and just work with this data for the next PostBack actions. So you don't have to worry about changes that may occur while browsing the Grid.

Resources