delete row's in RepeaterControl in ASP.net - asp.net

I write this code for delete from repeater,but I have a problem.
when I run my page ad delete one of rows , this row is deleted and when I refresh that page , another one rows deleted that I don't want delete that.in fact I want to delete one row but delete two row when I refresh page
protected void SendBoxrep_ItemCommand(object source, RepeaterCommandEventArgs e)
{
MembershipUser Admin = Membership.GetUser(User.Identity.Name);
if (e.CommandName == "del")
{
Guid g = new Guid(e.CommandArgument.ToString());
MessageClass.deleteMessage(g);
SendBoxrep.DataSource = MessageClass.selectMessagesUser(Admin);
SendBoxrep.DataBind();
}
}
public static void deleteMessage(Guid id)
{
foreach (Message item in MessageClass.LoadAll(id))
{
MDB.Messages.DeleteOnSubmit(item);
MDB.SubmitChanges();
}
}

In a scenario like this, I've had success using Response.Redirect to reload the page and get rid of the postback information after the postback event has been handled. This way the postback will happen only once and refreshing the page using the browser shouldn't cause any problems. Instead of calling the Repeater.DataBind...
Response.Redirect(Request.RawUrl);
You may have to make design changes to other parts of your page or add a parameter to the query string indicating that you are reloading the page, but that's the tax of providing this ability.

Try to delete based on primary key of the table u r deleting.
Suppose u r deleting a table say Messages which has messageID as primary key.
Now if u want to delete a particular message then send the messageID as commandArgument and delete that.
After delete when you r refreshing the page the same event occurs i.e. if you press a delete button in a row to delete the message the event SendBoxrep_ItemCommand fired and taking the commandArgument it deletes the record. Again you press F5 to refresh the page then the previous event for delete is fired. So your two records are being deleted.
Now using primary key (messageID) it will delete only one record even if you fire the same event twice by pressing F5.

Comments above show you're refreshing your page via F5; this is known to cause problems on ASP.NET pages because of how they post back, an how their lifecycle works. I recommend instead creating a Refresh button on the page itself, that does the postback and updates the necessary information the Repeater is bound to.

Related

Table Not Updating With Manual Save Mode

So I have a table that shows the entries. Users click on a button to open a fragment page to edit the data.
app.datasources.SystemOrders.selectKey(widget.datasource.item._key);
app.showDialog(app.pageFragments.SystemOrders_Edit);
This part works fine.
I have changed my datasource to Manual Save Mode to be able to utilize the "email notification for changes" functions that are used in the Project Tracker sample. So that a user can make changes, hit a Save (Close) Button and an email goes out showing the changes.
The problem is that when the user closes the fragment, the table does not update (they have the same datasource). When I was in automatic save mode, I was able to utilize the following to force the table to reload so it reflected any changes:
var datasource = app.datasources.SystemOrders_HideComplete;
datasource.load();
app.closeDialog();
So I figured I just needed to add the widget.datasource.saveChanges(); option for the Close Button.
widget.datasource.saveChanges();
var datasource = app.datasources.SystemOrders_HideComplete;
datasource.load();
app.closeDialog();
Unfortunately, when I use the above I get the following error and the table seems like it gets stuck trying to reload (the spinner keeps spinning).
"Cannot query records on models with changes."
I'm assuming this is maybe because the datasource hasn't finished saving the new change, before trying to reload the datasouce?
How can I have the Save (Close) Button:
Save the changes
Close the dialog
Refresh the table so it reflects the changes?
Thank you for your help.
You can try to refresh datasource in save callback(assuming that you are actually sharing datasource between page fragment and page):
widget.datasource.saveChanges(function() {
widget.datasource.load();
app.closeDialog();
});
That error will happen if your datasource is trying to refresh while you have unsaved changes.
I know your code block calls a client-side saveChanges before loading the datasource again, but you may need to check to make sure that the datasource is not being reloaded elsewhere at the same time.
If that hasn't fixed it, try passing the values to a server-side script and save the changes after assigning the properties, like this:
Client:
function handleSuccess() {
// ensures that records are saved, now reload
app.models.YourModel.YourDatasource.load();
}
google.script.run.withSuccessHandler(handleSuccess).addItem(field_value1, field_value2, field_value3);
Server:
function addItem(field_value1, field_value2, field_value3) {
// create new items
var newItem = app.models.YourModel.newRecord();
// assign values
newItem.field1 = field_value1;
newItem.field2 = field_value2;
newItem.field3 = field_value3;
// save
app.saveRecords([newItem]);
}
I've found this method to be more reliable than manipulating changes from the client script.

Deselecting a date in an ASP.Net Calendar catching a second click

I am working in n ASP.Net app. where selecting a date on a Calendar means that a task has been completed so that record goes to a SQL Database. However, sometimes users select a date by mistake so I need to give them the opportunity to deselect the date somehow.
I thought that the most natural way to let users to do this, is to click again in the selected date.
I tried to implement this through the "SelectionChanged" Calendar's event but it did not triggered clicking again on the selected date, which makes sense because actually the selected date did not change.
Then I tried using the "DayRender" event. So, I compare SelectedDate with VisibleDate, clearing the dates if both properties have the same date and selects the date otherwise.
It works the first time that the event is called, but then the event is triggered again when the next day has to be rendered and clears the date :D
protected void Claim_Edit_PickupDone_Calendar_DayRender(object sender, DayRenderEventArgs e)
{
Calendar cal = (Calendar)sender;
if (cal.SelectedDate == cal.VisibleDate)
{
cal.SelectedDates.Clear();
cal.VisibleDate = DateTime.MinValue;
}
else
{
cal.VisibleDate = cal.SelectedDate;
cal.SelectedDayStyle.BackColor = System.Drawing.Color.Goldenrod;
}
}
I also placed a checkbox inside the template, but it seems unnatural to me.
Could somebody please help me to catch the second click? Or maybe it would be better to leave the checkbox?
Best regards.
The trick is to write good logic rather than doing arbitrary code.
I would prefer writing TextBox_TextChanged event to check if the TextBox is empty, and fire a DB call to clear the Date field.
On the contrary you can use the solution implemented here in this topic.

How to prevent calling of function on every postback request

I have bind complete menu on postback now every post back request function
call and bind menu again i want to call it only first time please suggest
here below is my code
if (!Page.IsPostBack)
{
objCommon = new Common();
Common.UpdateLoginSession();
if (hiddenMenuFlag.Value == "S")//used hidden field but not working as is
//does not retain value on post back please suggest
{
BindMenu("0");//here is function for binding menu
hiddenMenuFlag.Value="";
}
}
use
if (!IsPostBack)
{
--------------------------;
--------------------------;
}
All functions or code inside this condition will run only for the first time, when page is requested. It won't execute on reload.
If you want to run a code only once; when the user request the page then you can use some session as suggested above.
If you want to run a code only for the first time when application runs, then you can use Application state to control your code
You could create a session variable and then check that variable to ensure your code will execute only once.
You create session variable like this:
Session["myVar"] = "myText";
And then you could check it value like below:
((string)Session["myVar"]) == "myText"

Execute function on specific key stroke in VB

I'm developing a web application that displays items from a work queue to a user. When an item is selected I have the app lock that item out so no other user can select it. By hitting the back button in the app it unlocks the item.
I want to be able to unlock the item if the user hits the backspace key. I know what code I need to unlock it. I just need to know how to make the code execute on backspace key stroke.
The code that I need to execute will be server side code.
Thanks in advance.
<script>
document.onkeydown = function (e)
{
if (window.event && window.event.keyCode == 8) {
__doPostBack('__Page', 'MyCustomArgument');
}
}
</script>
If you need to execute code on server, you have to change your question accordingly
EDIT:
You could set a Hiddenfield's value to f.e. "unlockItem" and do a document.forms[0].submit() and checkthe hidden-value on serverside or better:
Use the clientside __doPostBack function generated from ASP.Net to submit page(for example on selectedIndexChanged of a DropDownList). You could even generate it from Codebehind if you want the cleanest way.
I changed the above code, but i think your next question could be how you should know which item was selected, won't it?
Then you have to clarify what items we are talking about.
On serverside you get the passed arguments with:
If Page.IsPostBack Then
Dim eventArg As String = Request("__EVENTARGUMENT")
End If
End If

ASP.NET variable scope

im really new to ASP.Net and still havnt got my head round most of the concepts, im really having problems with variable, when creating a desktop application, any variable created in code for example
int n = 10;
this variable will be there until the program is running right. but in asp iv created variables which are supposed to last until the user gets of that page, so for example say i have a page which takes the users value ( call this variable n say the user type in 10) and every time the user presses the next button the code add 10 to this value. so the first time the user presses the next button
n= n + 10;
what i have found is no matter how many times i press the next button n will always equal 20, because the previous value is not saved !!
these values are populated the first time the user enters that page, once the user clicks the next button the content of these values disappear! how can stop this from happening ??
hope this makes sense !!
thanks
Every time you refresh page (click also refreshes page) new instance of Page class is created. This means that all your fields become empty.
You can try to use ViewState to persist data between refreshes. But you should be care as this will increase page size. So best practice is to minimaze data in view state.
Another options is SessionState, but in this case you will keep data even between pages.
Hope this helps.
Each time the user requests the page, it receives the request, is initialized, processed, and then rendered (read about the Asp.Net Page Life Cycle here.). So, on each page request, your variables are being created, initialized, and then assigned your values - each page load is a new life cycle. If you want values to persist betwen page life cycles, then you need to use one of the available methods (ViewState, Session, QueryString, Post, ....) to pass the values to the "next" request.
Variables don't automatically maintain state across page calls in ASP.NET. Asp.Net Page has a life cycle and being stateless, the information is lost at the end of this cycle, after a request has been served on the client side. There are several solution for this.
session
hidden fields
querystrings
Here is hidden field example.
In HTML, you simply create:
<input type="hidden" id="myHiddenVar">
To set it's value in javascript:
document.getElementById("myHiddenVar").value = "myValue"
In ASP.NET code-behind, you use the Request object to retrieve the value.
string myHiddenVar = (string)Request.Params["myHiddenVar"];
Variables in ASP.NET work exactly the way that variables in Windows Forms work:
public class MyPage : System.Web.UI.Page
{
private int n = 0;
public void Button_Click(object sender, EventArgs e)
{
n = n + 1;
}
}
public class MyForm : System.Windows.Forms.Form
{
private int n = 0;
public void Button_Click(object sender, EventArgs e)
{
n = n + 1;
}
}
So, why is it with the page, that the old value of "n" is gone the next time you hit the page?
Because HTTP is a request/response protocol. Each request creates a new instance of your MyPage class, each with its own copy of "n". In a Windows Forms application, you're probably not creating a new instance of your form on every button click!

Resources