Fire event with repeater - c#

I'm using a Repeater, there is a button for each item. When I click on one of these buttons asp.net returns me the following error:
Invalid postback or callback argument
But when I add the Page directive EnableEventValidation = "false" on my page, no error but does not fire my event.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] != null)
{
Customer activeCustomer = (Customer)Session["user"];
Response.Write("Welcome " + activeCustomer.FirstName + " " + activeCustomer.LastName + " | Offer count:" + activeCustomer.OfferLimit);
if (!IsPostBack)
{
ProdRepeater.DataSource = CampaignDataProcess.getDailyCampaign();
ProdRepeater.DataBind();
}
}
else
{
Response.Redirect("Login.aspx");
}
}
I have already tried if(!IsPostBack) in page load.
How can this be resolved?

if you are using more than form in your aspx file, you can not use your events. I had a problem like your and i solved my problem deleting that form tags.

Related

asp.net C# update textbox value without refresh

I have a website where there are two pages, page1 contain textbox and button1,
if I cliked button1 it will open page2 which contain button2,
if I cliked button2 it will assign value from page2 to the textbox in page1
but the problem is the value will display in the textbox after I refresh page1,
and my question is how I can update textbox value directly without refresh in page1 after I click button2 in page2 like this:
here is my code:
page1 aspx.cs:
<script type="text/javascript">
function openPopup() {
window.open("page2.aspx", "_blank", "WIDTH=1080,HEIGHT=790,scrollbars=no, menubar=no,resizable=yes,directories=no,location=no");
}
<asp:button text="clik" id="button1" runat="server" onclientclick="return openPopup()" xmlns:asp="#unknown" style="margin-right:30%" />
protected void Page_Load(object sender, EventArgs e)
{
if (Session["userID"] != null)
{
txtbox.Text = HttpContext.Current.Session["userID"].ToString();
}
}
page2:
protected void button2(object sender, EventArgs e)
{
Session["userID"] = row.Cells[0].Text;
}
we can do this in following way:
create a javascript function on page 2, that refresh textbox1 on
page 1.
on button2 click from page 2, using scriptmanager, call
the function created in step 1 with require param.
So, basically you code be like:
// place this in page2.aspx
// javascript function to update text box in page 1;
function UpdateParentText(value){
if(typeof(value) != undefined){
window.opener.document.getElementById("TextBox1").value=value;
}
}
//2. code behind call to the javascript function from page2.cs
protected void button2(object sender, EventArgs e)
{
// code behind call to the javascript function.
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "MyScript", "UpdateParentText('" + row.Cells[0].Text + "'", true);
}
If you are not using AJAX, then use this:
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", "UpdateParentText('" + row.Cells[0].Text + "'", true);
You may use:
window.postMessage() — to send the message
window.addEventListener(“message”,callback) — to receive and process the message
See sample here.
thanks everyone I solve it by using session with javascript

button action not firing

I have a web form which dynamically loads controls upon selection in combobox(devexpress). I have the following code on main form
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
if (Session["_active_control"] != null)//persist control on postbacks
{
Control cntrl = Session["_active_control"] as Control;
pnl_main.Controls.Clear();
pnl_main.Controls.Add(cntrl);
}
}
protected void cmb_control_SelectedIndexChanged(object sender, EventArgs e)
{
Control cntrl= Page.LoadControl("~/" + cmb_control.SelectedItem.Value);
pnl_main.Controls.Clear();
pnl_main.Controls.Add(cntrl);
Session["_active_control"] = cntrl;
}
also I have a user control having three Textboxes and a button having code
protected void btn_save_Click(object sender, EventArgs e)
{
lbl.Text = ASPxTextBox1.Text + "<br>" + ASPxTextBox2.Text + "<br>" + ASPxTextBox3.Text;
}
My problem is that the save button of user control is not firing if i load it dynamically (I have checked using breakpoints and also the code shown above. however it runs smoothly if I use it statically.(i.e. by dragging in design mode)
You are right that you have to persist the control across postbacks.
However the Page Load event is too late to add back your controls. Do this on the Init event of your page and you should be good. To receive a postback event, the control should be present when ProcessPostData(called before PreLoad) is called.
Also for textboxes you will want to receive the values entered by the user. This too happens on ProcessPostData, if you add you control after that, you will not receive the values entered by the user.
Refer: ASP.NET Page Life Cycle
hey i found the solution
instead on creating the controls in combobox_selectedindexchanged i put my control creation code on Pageload based in combobox.selectedindex i.e.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (cmb_control.SelectedItem != null)
{
Control cntrl = Page.LoadControl("~/" + cmb_control.SelectedItem.Value);
cntrl.ID = "_new_ctrl" + cmb_control.SelectedItem.Value;
pnl_main.Controls.Clear();
pnl_main.Controls.Add(cntrl);
}
}
see Button click event not firing within use control in ASP .Net

Messagebox from master page

How to display a messagebox from the ASP.net(C#) master page itself. I mean when a link button on the master page is clicked a message box is to be displayed. i've tried calling the following method with no result.
public void MessageBox(string message, Page page)
{
if (!string.IsNullOrEmpty(message))
{
Label lbl = new Label();
lbl.Text = "<script type=\"text/javascript\" language=\"javascript\">"
+ "alert('" + message + "'); " + "</script>";
page.Controls.Add(lbl);
}
}
Either register the OnClientClick to the LinkButton, then the alert will be shown before the postback, or register the alert-script in the Click-Event handler during postback, so that the alert will be shown as soon as the page is rendered to the client the next time:
protected void Page_Load(object sender, System.EventArgs e)
{
MyButton.OnClientClick = "alert('MyButton clicked!');";
}
protected void MyButton_Click(object sender, System.EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "AlertScript", "alert('MyButton clicked!');", true);
}
I just put your code into a page and it worked with no problem. It was not a master page but I see no difference in why it wouldn't work in a master page just as well. Here is the code that worked for me:
The linkbutton in the page:
<asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">LinkButton</asp:LinkButton>
The code behind:
public void MessageBox(string message, Page page)
{
if (!string.IsNullOrEmpty(message))
{
Label lbl = new Label();
lbl.Text = "<script type=\"text/javascript\" language=\"javascript\">" + "alert('" + message + "'); " + "</script>";
page.Controls.Add(lbl);
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
MessageBox("test", Page);
}
You should use ClientScriptManager.RegisterClientScriptBlock to add scripts to the page instead of literal controls with javascript values.
I'd suggest a base class for your master page, something like:
public sealed class MasterPageBase : MasterPage
{
protected void AddAlertMessage(string Message)
{
var script = String.Format("alert('{0}');", Message);
this.Page.ClientScript
.RegisterStartupScript(this.GetType(),"PageAlertMessage",script,true);
}
}
Now set this as your base across your master pages, and you can call:
protected void LinkButton1_Click(object sender, EventArgs e)
{
this.AddAlertMessage("Hello");
}
The main benifit is that the script details are abstracted away, and you can easily make global changes to them (switching to a Growl Style alert for instance) without making many page edits.
On the page load of master page write the following code
lnkButton.Attributes.Add("onclick","alert('message');");
The following code worked for me.
linkbutton1.OnClientClick ="javascript:alert('Hello')"

Preserving Button's Text on Postback

I can't for the life of me figure this out! What I want to do is on the first page load set the button's text and the label's text to the current time. However, when the user clicks the button, only the label's text is updated to the current time and the button's text remains the time of when the page first loaded. I know I can do this with Ajax but i know there is way to do it just using the IsPostBack method. Can anyone help me?
public partial class TestPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Button1.Text = "Initial Page Load Time: " + DateTime.Now.ToLongTimeString() + ". (Click to update current time in Label)";
Label1.Text = "Current Time: " + DateTime.Now.ToLongTimeString();
}
Add a HiddenField to your page, then change your code to;
protected void Page_Load(object sender, EventArgs e)
{
if ( !Page.IsPostBack ){
HiddenField1.Value = "Initial Page Load Time: " + DateTime.Now.ToLongTimeString() + ". (Click to update current time in Label)";
}
Button1.Text = HiddenField1.Value;
Label1.Text = "Current Time: " + DateTime.Now.ToLongTimeString();
}
The HiddenField value will be preserved on PostBack so you can set the button text from this.
Just add this before setting the text:
if (Page.IsPostBack)
return

On ASP.NET form submit it throws an Object reference not set to an instance of an object.

I have a simple email form written in ASP.NET with the logic in the codebehind file. It's all in C# (the logic that is...). Anyways, on page load I have the following:
protected void Page_Load(object sender, EventArgs e)
{
RequestorName.Text = Request.Form["UserName"].ToString();
RequestorTitle.Text = Request.Form["JobTitle"].ToString();
RequestorEmail.Text = Request.Form["Email"].ToString();
RequestorPhone.Text = Request.Form["Phone"].ToString();
RequestorAddress1.Text = Request.Form["Address"].ToString();
RequestorAddress2.Text = Request.Form["City"].ToString() + " " + Request.Form["State"].ToString() + ", " + Request.Form["Zip"].ToString();
}
This works great as it pulls the users information into a few fields so they don't have to fill everything out by hand.
My other 2 methods in the code behind:
protected void SubmitForm_Click(object sender, EventArgs e)
{
SendEmail();
}
protected void SendEmail()
{
try
{
//compose email and send
}
catch (Exception ex)
{
ErrorMessage.Text = "Error: " + ex.ToString();
}
}
On my form page the button code is this:
<center>
<asp:Button runat="server" Text="Submit" ID="Submit" OnClick="SubmitForm_Click" class="button red" />
</center>
The error occurs when I click the send button on the form that generates the email and sends it. I can remove the Page_Load code and works great but I'd like to keep it there so the user doesn't have to fill out as much information.
I've used my Google Fu and read a ton of threads/articles but can't seem to find the solution...
Thanks for any assistance.
Add check for IsPostBack:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RequestorName.Text = Request.Form["UserName"].ToString();
RequestorTitle.Text = Request.Form["JobTitle"].ToString();
RequestorEmail.Text = Request.Form["Email"].ToString();
RequestorPhone.Text = Request.Form["Phone"].ToString();
RequestorAddress1.Text = Request.Form["Address"].ToString();
RequestorAddress2.Text = Request.Form["City"].ToString() + " " + Request.Form["State"].ToString() + ", " + Request.Form["Zip"].ToString();
}
}
Have you tried adding if (Page.IsPostBack == false) to your Page_Load event?
I assume that the Request.Form code comes from fields that the user has filled out, but without seeing the rest of your markup, I'm not sure why you'd have to re-assign values from the form to what appear to be other fields on the form.
Where specifically is the error occurring?
From your code, I'm assuming that you are posting to your email form from another page and passing the parameters across.
If that's the case then assuming your .Text are the page controls then you should look at containing the control fillers in an If(!IsPostback) {...} for the first loading of the page only. Then your email code can read from the local controls.
My guess is that the "Request.Form[..." items are probably the ones kicking back error on postback.
HTH
Dave

Categories

Resources