Duplicate PK Check on saving - Alert not firing - asp.net

I'm trying to check for duplicate pks when trying to insert a new record. I want to show an error if it does, but i'm not sure where i am going wrong/if this is the right way to go.
Please see below. I put a breakpoint at the function AgentSave_Click and saw its its not going into the IF statement
<asp:Button ID="AgentSave" runat="server" CausesValidation="true" OnClick="AgentSave_Click" Style="margin-left: 0px" Text="Save" />
protected void AgentSave_Click(object sender, EventArgs e)
{
try
{
if (AccountNumber.Text.Trim().Equals("select PRIMARYKEYNAME from TABLEXYZ"))
{
Response.Write("<script type=\"text/javascript\">" + "window.alert('ERROR: The Account Number entered is already assigned to an Agent.');" + "</script>");
AccountNumber.Focus();
}
else
{.....

OnClientClick property is meant to execute some javascript code on client before data is send back to server.
According your answer you are trying to execute server code. So you should replace onclientclick with onclick="duplicate_PK" which gets executed on server.
Regards,
Uros

<asp:Button ID="AgentSave" runat="server" OnClick="AgentSave_Click" Style="margin-left: 0px" Text="Save" />
remove CausesValidation="true" or chANGE TO CausesValidation="false"

Related

Disable Button after click in dnn

for one requirements i need to disable button after click and run server side code after disabled for this i have used below code which is called at pageload
btnGREntry.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(btnGREntry, "") +
";this.value='Please wait...';this.disabled = true;");
but it is giving me below error.
An unknown error occurred while processing the request on the server.
The status code returned from the server was: 0
please help me to find out a solution or suggest any other solution to disable button after click
Note: similar things are working in asp.net but i am using in *dotnetnuke version 7.0 *
You can do this in the code-behind.
ASPX
<asp:Button ID="Button1" runat="server" onclick="Button1_Click1" Text="Button" />
Code-behind
protected void Button1_Click1(object sender, EventArgs e)
{
Button a = (Button)sender;
a.Enabled = false;
}
Does the button have to remain disabled continuously or is it to return to enabled after page refresh? In the former case then handle it with both JavaScript and code behind. In the later case handle it with just JavaScript.
<asp:Button ID="Button1" runat="server" onClientClick="DisableButton();" onclick="Button1_Click1" Text="Button" />
JavaScript:
function DisableButton() {
var btn = $("#buttonID").attr("disabled", "disabled");
}

Two Buttons updating one item of a listview

I have two buttons in a ListView. With a click on the first Button I want to update the ListView-Item. With a click on the second button i want to update the ListView-Item and redirect to a different page. Both Buttons have a property CommandName="Update". I wanted to solve my problem with the CommandArgument-Property and the OnItemUpdated-Event, but I do not know how to get the value of this Property in the event.
<asp:ObjectDataSource ID="ods" runat="server" SelectMethod="Select" UpdateMethod="Update">
<SelectParameters>
<asp:Parameter ..... />
</SelectParameters>
<UpdateParameters>
<asp:Parameters .... />
</UpdateParameters>
</asp:ObjectDataSource>
<asp:ListView ID="lv" runat="server" DataSourceID="ods" DataKeyNames="ID" OnItemUpdated="lv_OnItemUpdated">
<ItemTemplate>...</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btnUpdate" runat="server" CommandName="Update"/>
<asp:Button ID="btnUpdate2" runat="server" CommandName="Update"/>
</EditItemTemplate>
</asp:ListView>
And in codebehind:
protected void lv_OnItemUpdated(object sender, ListViewUpdateEventArgs e)
{
...
}
Is it possible to decide in lv_OnItemUpdated which Button the user clicked?
I don't believe there is a way to distinguish which control issued the Update command, since sender is the ListView itself.
A workaround would be for you to give one button the CommandName "Update", and the other "UpdateRedirect".
The "UpdateRedirect" button will fire the ListView_ItemCommand event, and from there you can call ListView.UpdateItem, keeping your updating logic in there, and then redirect next.
Why do you insist on using the OnItemUpdated event?
Well there are 2 to 3 ways of doing it: One is of CommandArgument as:
<asp:Button id="Button1"
Text="Sort Ascending"
CommandName="Sort"
CommandArgument="Ascending"
OnCommand="CommandBtn_Click"
runat="server"/>
<asp:Button id="Button2"
Text="Sort Descending"
CommandName="Sort"
CommandArgument="Descending"
OnCommand="CommandBtn_Click"
runat="server"/>
and than on server side you can have:
void CommandBtn_Click(Object sender, CommandEventArgs e)
{
if(e.CommandName == "Sort")
//do you work and so on
}
or you can cast the sender as button and take it ID to see, which button was it:
((Button)sender)).ID
or you can get button ID as:
String ButtonID = Request["__EVENTTARGET"];
I hope it will help you in fixing your problem.
so you can have like:
protected void lv_OnItemUpdated(object sender, ListViewUpdateEventArgs e)
{
// either use e.CommandName
// or user ((Button)sender)).ID
}
Give each button a distinct name. Have the same event handling method in your code behind handle both button click events. Then check which button called the method.
EDIT: A workaround would be to use javascript to put the name of the clicked button into a hidden field on the form BEFORE it goes server side (using a client side script). Then in your Listview you could check the value of the hidden field to see which button was clicked.
Ok, yes, the itemcommand is what you want:
The lifecycle for an update or insert triggers both their native events AND the itemcommand event. The itemCommand event will occur prior to the itemUpdating or the itemInserting events.
So, you can create a boolean variable called called "bSecondButtonClicked" for example Add the command argument to both buttons with the Commandname='UPDATE". the e.command argument can be evaluated at the itemcommand event point. There set your Boolean variable (or however you implement it) to true. Then, at the itemupdating event, trigger your code based on the bSecondButtonClicked.
You need to get into the ItemCommand event of your ListView
protected void lstvw_ItemCommand(object sender, ListViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "new":
try
{
//e.CommandArgument
//e.CommandSource
// do your stuff here
}
catch (Exception ex)
{
}
break;
default:
break;
}
}

How to avoid Page_Load() on button click?

I have two buttons, preview and Save. With help of preview button user can view the data based on the format and then can save.
But when preview is clicked, one textbox attached to ajaxcontrol (Calender) becomes empty and user have to fill the date before saving. How to handle this? On preview click i get the details to show the data in layout.
<asp:TextBox ID="txtDate" ReadOnly="true" runat="server"></asp:TextBox>
<div style="float: right;">
<asp:ImageButton ID="imgcalender1" runat="server" ImageUrl="~/images/calendar.png"
ImageAlign="Bottom" />
<asp:CalendarExtender ID="ajCal" TargetControlID="txtpublishDate" PopupButtonID="imgcalender1"
runat="server">
</asp:CalendarExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ValidationGroup="group1" runat="server" ControlToValidate="txtDate"
ForeColor="Red" Font-Bold="true" ErrorMessage="*"></asp:RequiredFieldValidator>
</div>
<asp:Button ID="btnPreview" runat="server" Text="Preview" OnClick="btnPreview_Click" />
<asp:Button ID="btnsubmit" runat="server" ValidationGroup="group1" Text="Save" OnClick="btnsubmit_Click" />
Use Page.IsPostback() in your aspx code (server-side). Like this:
private void Page_Load()
{
if (!IsPostBack)
{
// the code that only needs to run once goes here
}
}
This code will only run the first time the page is loaded and avoids stepping on user-entered changes to the form.
From what I am understanding the preview button is causing a postback and you do not want that, try this on your preview button:
<asp:button runat="server".... OnClientClick="return false;" />
similarly this also works:
YourButton.Attributes.Add("onclick", return false");
Edit:
it seems the answer to the user's question was simple change in the HTML mark up of the preview button
CausesValidation="False"
you can put your code in
Page_Init()
{
//put your code here
}
instead of
Page_Load()
{
//code
}
I had the same problem and the solution above of "CausesValidation="False"" and even adding "UseSubmitBehavior="False"" DID NOT work - it still called "Page_Load" method.
What worked for me was adding the following line up front in Page_Load method.
if (IsPostBack) return;
I am mentioning this if it helps someone (I meant to comment above but StackOverflow did not allow me to comment because I am a new user - hence a new reply).
Try adding this to the buttons properties in the aspx page.
OnClientClick="return false;"
For my the #tgolisch answer worked better, maybe it's because i'm still a rookie.
I was trying to load a simple captcha in my WebForm and end up using a Reference Type in the Page_Load event and in a Button Click event (for a code snippet).
In the end i only have to edit some things and it's done:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var captchaText = generateCaptchaCode(5);
lblCaptcha.Text = captchaText;
}
}
protected void btnCheckCaptcha_Click(object sender, EventArgs e)
{
if (txtCaptchaCode.Text == lblCaptcha.Text)
lblMessage.Text = "Right input characters";
else
lblMessage.Text = "Error wrong characters";
}
form1.Action = Request.RawUrl;
Write this code on page load then page is not post back on button click

ASP.NET confirmation box showing twice

I've searched for a way to display a confirmation box when a certain button is pressed.
The only problem I have, is that the confirmation box shows twice.
Code:
<dx:ASPxButton ID="btnDel" runat="server" onClick="btnDel_Click" Text="Delete">
and in Page_Load:
btnDel.Attributes.Add("onclick", "return confirm('Are you sure?');");
Change your Page_Load code to:
if (! IsPostback)
btnDel.Attributes.Add("onclick", "return confirm('Are you sure?');");
You only have to add the onclick attribute once at the first load of the page.
the button control you are using is devexpress button and it implements it's own ClientSideEventCollection in which you can add any javascript. you can do it like following
<dx:ASPxButton ID="btnDel" runat="server" onClick="btnDel_Click" Text="Delete">
<ClientSideEvents Click="function(s, e) {
e.processOnServer = confirm('Are sure to save data?');
}" />
</dx:ASPxButton>
Here e.processOnServer is a boolean which decides if the server trip should be executed, so we assigned the result of confirm to this boolean.
you can find more about ClientSideEvents on a dev express control, in the devexpress docs here

Sending parameter to code behind from stored procedure

I'm using a FormView and binding it to a SqlDataSource using a stored procedure to edit a record. The thing is that after updating the record I need to call another function, which I'm doing using the onClick attribute of the button.
This function has to insert a few records into another table, using the ID of the record edited in the FormView. I know how to use SCOPE_IDENTITY when in the same stored procedure, but this time I need some logic that is easier to accomplish in the code-behind, but I don't know how to obtain the ID, so any leads would be great.
Here is the button:
<asp:Button ID="EditButton" runat="server" CausesValidation="True" CommandName="Update"
Text="Edit" OnClick="setProcessProgress" />
And here is a stripped down version of the code behind:
protected void setProcessProgress(object sender, EventArgs e)
{
int ID_p;
ID_p = ; //TODO: Here I need to obtain the ID of the last edited record from the EditButton
setProgress(ID_p);
}
The stored procedure is a simple UPDATE statement.
I'm thinking of passing a parameter to the code behind, but not sure how to, perhaps something like this OnClick="setProcessProgress(#id)"
try like this, and you need to attach OnCommand="CommandEventHandler" event handler to your button . check for More Info Button.Command
<asp:Button ID="EditButton" runat="server" CausesValidation="True" CommandName="Update"
Text="Edit"
CommandArgument="1"
OnCommand="CommandBtn_Click" />
and the code for to get the ID
protected void CommandBtn_Click(Object sender, CommandEventArgs e)
{ if (e.CommandName == "Update")
{
yourID =Convert.ToInt32(e.CommandArgument);
}
}
You can use out parameter for update store procedure. This will give you the ID after
update.
Then you can use the ID for your insert.
http://blogs.msdn.com/b/spike/archive/2009/05/07/a-simple-example-on-how-to-get-return-and-out-parameter-values-using-ado-net.aspx

Resources