SelectedIndexChanged not firing - asp.net-2.0

My problem is that SelectedIndexChanged of ddlObra control is not firing, but when I erase the Page.ClientScript.RegisterOnSubmitStatement of Page_Load, everything works fine. I can't understand this behavior.
Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CarregarDropDownLists();
}
Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "OnSubmitScript", "return handleSubmit()");
}
protected void ddlObra_SelectedIndexChanged(object sender, EventArgs e)
{
List<Entidades.Empreendimento.Unidade> unidades = Entidades.Empreendimento.Unidade.ListaUnidades(txtLogin.Text);
ddlBloco.Items.Clear();
ddlUnidade.Items.Clear();
ddlBloco.Items.Insert(0, new ListItem("----- Bloco -----", ""));
ddlUnidade.Items.Insert(0, new ListItem("----- Unidade -----", ""));
//if (unidades.Count == 1) return;
foreach (Entidades.Empreendimento.Unidade Un in unidades)
{
if (Un.ObraVinculo.idObraCrm.ToString() == ddlObra.SelectedValue)
{
if (!ddlBloco.Items.Contains(new ListItem(Un.BlocoCRM.Nome, Un.BlocoCRM.CodigoCRM)))
{
ddlBloco.Items.Add(new ListItem(Un.BlocoCRM.Nome, Un.BlocoCRM.CodigoCRM));
}
Bandeira = Un.Bandeira;
Estado = Un.Estado;
}
}
ddlBloco.SelectedIndex = 0;
ddlUnidade.SelectedIndex = 0;
LoadAreas();
}
This code is in the .aspx file
<script type="text/javascript">
function handleSubmit() {
if (typeof (ValidatorOnSubmit) == 'function' && ValidatorOnSubmit() == false) {
return false;
} else {
$("#btnEnviar").click(function () { return false }).fadeTo(200, 0.5);
return true;
}
}
</script>
Thank you guys for your help!

The client script executed by the submission of the form must return true in
order to allow the form to submit. This enables the client-side script to
prevent the submission of the form conditionally.

Related

crystal report viewer next page not working

I am using visual studio 2010 and crystal report 13.0
The report viewer displays the first page properly. But the next page button is not working. If i click on next page button then it shows loading message and stays there only.None of the report viewer controls are working.
please help me out
I found the solution.
Manually add the Page_Init() event and wire it up in the InitializeCompnent() with
this.Init += new System.EventHandler(this.Page_Init).
Move the contents of Page_Load to Page_Init().
Add if (!IsPostBack) condition in PageInIt.
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
ReportDocument crystalReportDocument = new ReportDocumment();
crystalReportDocument.SetDataSource(DataTableHere);
_reportViewer.ReportSource = crystalReportDocument;
Session["ReportDocument"] = crystalReportDocument;
}
else
{
ReportDocument doc = (ReportDocument)Session["ReportDocument"];
_reportViewer.ReportSource = doc;
}
}
Instead of manually identifying the moment to bind, you could use the CrystalReportViewer AutoDataBind property in combination with the DataBinding event.
Autobind definition:
// Summary:
// Boolean. Gets or sets whether automatic data binding to a report source is
// used. If the value is set to True, the DataBind() method is called after
// OnInit() or Page_Init().
[Category("Data")]
[DefaultValue(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public bool AutoDataBind { get; set; }
You could use this property in the following manner:
In the ASPX:
<CR:CrystalReportViewer ID="_reportViewer" runat="server" AutoDataBind="true" OnDataBinding="_reportViewer_DataBinding" />
And in the ASPX.CS:
protected void _reportViewer_DataBinding(object sender, EventArgs e)
{
if (!IsPostBack)
{
ReportDocument crystalReportDocument = new ReportDocumment();
crystalReportDocument.SetDataSource(DataTableHere);
_reportViewer.ReportSource = crystalReportDocument;
Session["ReportDocument"] = crystalReportDocument;
}
else
{
ReportDocument doc = (ReportDocument)Session["ReportDocument"];
_reportViewer.ReportSource = doc;
}
}
Done! Shift your Page load Event to Page Init Event.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
int pageIndex =((CrystalDecisions.Shared.PageRequestContext)
CrystalReportViewer1.RequestContext).PageNumber;
//Bind Report with filter and datasource
string ControID = GetPostBackControlName(this);
//get and check Crystal Report Navigation button event after Bind Report
if (ControID == null)
{
((CrystalDecisions.Shared.PageRequestContext)
CrystalReportViewer1.RequestContext).PageNumber = pageIndex;
}
}
}
public string GetPostBackControlName(Page Page)
{
Control control = null;
string ctrlname = Page.Request.Params["__EVENTTARGET"];
if (ctrlname != null && ctrlname != String.Empty)
{
control = Page.FindControl(ctrlname);
}
else
{
string ctrlStr = String.Empty;
Control c = null;
foreach (string ctl in Page.Request.Form)
{
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
ctrlStr = ctl.Substring(0, ctl.Length - 2);
c = Page.FindControl(ctrlStr);
}
else
{
c = Page.FindControl(ctl);
}
if (c is System.Web.UI.WebControls.Button ||
c is System.Web.UI.WebControls.ImageButton)
{
control = c;
break;
}
}
}
if (control == null)
{
return null;
}
else
{
return control.ID;
}
}

Using Global.asax to set/check session variable and redirect (for user testing)

I would like to add very simple, temporary security to my site.
I made a page at Home/UnderConstruction where people testing the site can enter a hard-coded password which will then set the "underconstruction" session variable to "false".
This is what I have so far, but it results in too many redirects:
protected void Session_Start(Object sender, EventArgs e)
{
HttpContext.Current.Session["underconstruction"] = "true";
}
protected void Application_AcquireRequestState(Object sender, EventArgs e)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
var underconstruction = HttpContext.Current.Session["underconstruction"];
if (underconstruction != null)
{
string oc = underconstruction.ToString();
if (oc != "false") Response.Redirect("~/Home/UnderConstruction");
}
}
}
Is this close to what I would need to do?
Here is the code we got to work:
Controller Code for UnderConstruction View
public ViewResult UnderConstruction()
{
return View();
}
[HttpPost]
public ActionResult UnderConstruction(string ocp)
{
if (ocp == "mypassword")
{
Session["underconstruction"] = "false";
return RedirectToAction("Index", "Home");
}
else
{
Session["beingredirected"] = "false";
return View();
}
}
Global.Asax
protected void Session_Start(Object sender, EventArgs e)
{
HttpContext.Current.Session["underconstruction"] = "true";
HttpContext.Current.Session["beingredirected"] = "false";
}
protected void Application_AcquireRequestState(Object sender, EventArgs e)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
bool uc = false;
var underconstruction = HttpContext.Current.Session["underconstruction"];
if (underconstruction != null)
{
uc = Boolean.Parse(underconstruction.ToString());
}
bool redirected = false;
var beingredirected = HttpContext.Current.Session["beingredirected"];
if (beingredirected != null)
{
redirected = Boolean.Parse(beingredirected.ToString());
}
if (uc && !redirected)
{
if (Request.HttpMethod == "GET")
{
HttpContext.Current.Session["beingredirected"] = "true";
Response.Redirect("~/Home/UnderConstruction");
}
else if (Request.HttpMethod == "POST")
{
}
}
HttpContext.Current.Session["beingredirected"] = "false";
}
}
Is ~/Home/UnderConstruction in a different website? If not, wont it always redirect because oc will always be true? ie - do you also need to add a check for the page you're requesting so you can bypass the redirect if already going to the UnderConstruction page?
UPDATE
Not sure if checking the page name is a great idea, but something like this might work:
protected void Session_Start(Object sender, EventArgs e)
{
HttpContext.Current.Session["underconstruction"] = "true";
HttpContext.Current.Session["beingredirected"] = "false";
}
protected void Application_AcquireRequestState(Object sender, EventArgs e)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
bool uc = false;
var underconstruction = HttpContext.Current.Session["underconstruction"];
if (underconstruction != null)
{
uc = Boolean.Parse(underconstruction);
}
bool redirected = false;
var beingredirected = HttpContext.Current.Session["beingredirected"];
if (beingredirected != null)
{
redirected = Boolean.Parse(beingredirected);
}
if (uc && !redirected)
{
HttpContext.Current.Session["beingredirected"] = "true";
Response.Redirect("~/Home/UnderConstruction");
}
HttpContext.Current.Session["beingredirected"] = "false";
}
}
Note that I would clean that up, that example was to just give the general idea.
UPDATE
If you want to use roles as mentioned in the comments, then this article from ScottGu's Blog may help. Its a little more complicated, but has the added benefit of not introducing temporary code as the above solution will

form post back related

I have one form with submit button in asp.net and C#. Form is for submitting comment to website webmaster through email. C# code is as below.
but facing one problem. i.e. on refreshing the page it again sends the comment in email due to postback. How can I avoid this? here is the code...
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string body = "";
//body = body + "<html><head></head><body>";
body = body + "Dear Balvignan Team,\r\n";
if (txtComment.Text != null)
{
body = body + "Comment: " + txtComment.Text;
}
if (SendEmail(txtEmail.Text.Trim(), "Comment", body, false) == true)
{
lblContactAcknowledge.Text = "Thank You For <br />Submitting comment.";
lblContactAcknowledge.Visible = true;
PnlTalkToUs.Visible = false;
}
else
{
lblContactAcknowledge.Visible = false;
PnlTalkToUs.Visible = true;
}
}
SendEmail is function to send email.
You can use the Page.IsPostBack Property to check, if its a Postback or page refresh.
You might use the following option:
if (SendEmail(txtEmail.Text.Trim(), "Comment", body, false) == true)
{
Response.Redirect("contact.aspx?success=true");
}
else
{
Response.Redirect("contact.aspx");
}
On Page Load
if (!Page.IsPostback)
{
if (Request.QueryString["success"] == "true" )
{
lblContactAcknowledge.Text = "Thank You For <br />Submitting comment.";
lblContactAcknowledge.Visible = true;
PnlTalkToUs.Visible = false;
}
else
{
lblContactAcknowledge.Visible = false;
PnlTalkToUs.Visible = true;
}
}
When the user refreshes the page (ctrl + r, f5, etc) will to a GET request, not a POST request.
EDIT another solution
Another solution is to use ViewState:
public bool EmailSent
{
get
{
return ViewState["EmailSent"] != null ? (bool)ViewState["EmailSent"] : false;
}
set
{
ViewState["EmailSent"] = value;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
....
if (!EmailSent)
{
if (SendEmail(txtEmail.Text.Trim(), "Comment", body, false) == true)
{
...
EmailSent = true;
}
else
{
...
}
}
}
In your page_load event
if(page.isPostback==NO)
{
//send an email
}
else
{
//Don't send
}

How to call ascx delegate to some other ascx btn click?

I have ascx suppose A.ascx in which i am writing a delegate on OnInit() like this
btnUpdate.Click += delegate
{
if (MaxLength.HasValue && txtText.Text.Length >= MaxLength.Value)
{
lblError.Text = string.Format(Resources.ErrorMessage_FieldLength, MaxLength);
return;
}
if (Update != null) Update(this, EventArgs.Empty);
};
Now I want to call this delegate on B.ascx btn click
protected void btnHdnAnswer_Click(object sender, EventArgs e)
{
// How to call above delegate..
}
Please help me in this
Make your delegate a proper method.
btnUpdate.Click += delegate { DoUpdate(); }
...
public void DoUpdate()
{
if (MaxLength.HasValue && txtText.Text.Length >= MaxLength.Value)
{
lblError.Text = string.Format(Resources.ErrorMessage_FieldLength, MaxLength);
return;
}
if (Update != null) Update(this, EventArgs.Empty);
}
Make sure the Id of your control is set to generate a member for it in the code-behind:
<Project:A runat="server" ID="MyBControl"/>
Then call it from your B (parent) control:
protected void btnHdnAnswer_Click(object sender, EventArgs e)
{
MyBControl.Update();
}

Saving State Dynamic UserControls...Help!

I have page with a LinkButton on it that when clicked, I'd like to add a Usercontrol to the page. I need to be able to add/remove as many controls as the user would like. The Usercontrol consists of three dropdownlists. The first dropdownlist has it's auotpostback property set to true and hooks up the OnSelectedIndexChanged event that when fired will load the remaining two dropdownlists with the appropriate values.
My problem is that no matter where I put the code in the host page, the usercontrol is not being loaded properly. I know I have to recreate the usercontrols on every postback and I've created a method that is being executed in the hosting pages OnPreInit method. I'm still getting the following error:
The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.
Here is my code:
Thank you!!!!
bool createAgain = false;
IList<FilterOptionsCollectionView> OptionControls
{
get
{
if (SessionManager.Current["controls"] != null)
return (IList<FilterOptionsCollectionView>)SessionManager.Current["controls"];
else
SessionManager.Current["controls"] = new List<FilterOptionsCollectionView>();
return (IList<FilterOptionsCollectionView>)SessionManager.Current["controls"];
}
set
{
SessionManager.Current["controls"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
Master.Page.Title = Title;
LoadViewControls(Master.MainContent, Master.SideBar, Master.ToolBarContainer);
}
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
System.Web.UI.MasterPage m = Master;
Control control = GetPostBackControl(this);
if ((control != null && control.ClientID ==
(lbAddAndCondtion.ClientID) || createAgain))
{
createAgain = true;
CreateUserControl(control.ID);
}
}
protected void AddAndConditionClicked(object o, EventArgs e)
{
var control = LoadControl("~/Views/FilterOptionsCollectionView.ascx");
OptionControls.Add((FilterOptionsCollectionView)control);
control.ID = "options" + OptionControls.Count.ToString();
phConditions.Controls.Add(control);
}
public event EventHandler<Insight.Presenters.PageViewArg> OnLoadData;
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
protected Control GetPostBackControl(System.Web.UI.Page page)
{
Control control = null;
string ctrlname = Page.Request.Params["__EVENTTARGET"];
if (ctrlname != null && ctrlname != String.Empty)
{
control = FindControlRecursive(page, ctrlname.Split('$')[2]);
}
else
{
string ctrlStr = String.Empty;
Control c = null;
foreach (string ctl in Page.Request.Form)
{
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
ctrlStr = ctl.Substring(0, ctl.Length - 2);
c = page.FindControl(ctrlStr);
}
else
{
c = page.FindControl(ctl);
}
if (c is System.Web.UI.WebControls.CheckBox ||
c is System.Web.UI.WebControls.CheckBoxList)
{
control = c;
break;
}
}
}
return control;
}
protected void CreateUserControl(string controlID)
{
try
{
if (createAgain && phConditions != null)
{
if (OptionControls.Count > 0)
{
phConditions.Controls.Clear();
foreach (var c in OptionControls)
{
phConditions.Controls.Add(c);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
Here is the usercontrol's code:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="FilterOptionsCollectionView.ascx.cs" Inherits="Insight.Website.Views.FilterOptionsCollectionView" %>
namespace Insight.Website.Views
{
[ViewStateModeById]
public partial class FilterOptionsCollectionView : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnInit(EventArgs e)
{
LoadColumns();
ddlColumns.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(ColumnsSelectedIndexChanged);
base.OnInit(e);
}
protected void ColumnsSelectedIndexChanged(object o, EventArgs e)
{
LoadCriteria();
}
public void LoadColumns()
{
ddlColumns.DataSource = User.GetItemSearchProperties();
ddlColumns.DataTextField = "SearchColumn";
ddlColumns.DataValueField = "CriteriaSearchControlType";
ddlColumns.DataBind();
LoadCriteria();
}
private void LoadCriteria()
{
var controlType = User.GetItemSearchProperties()[ddlColumns.SelectedIndex].CriteriaSearchControlType;
var ops = User.GetItemSearchProperties()[ddlColumns.SelectedIndex].ValidOperators;
ddlOperators.DataSource = ops;
ddlOperators.DataTextField = "key";
ddlOperators.DataValueField = "value";
ddlOperators.DataBind();
switch (controlType)
{
case ResourceStrings.ViewFilter_ControlTypes_DDL:
criteriaDDL.Visible = true;
criteriaText.Visible = false;
var crit = User.GetItemSearchProperties()[ddlColumns.SelectedIndex].SearchCriteria;
ddlCriteria.DataSource = crit;
ddlCriteria.DataBind();
break;
case ResourceStrings.ViewFilter_ControlTypes_Text:
criteriaDDL.Visible = false;
criteriaText.Visible = true;
break;
}
}
public event EventHandler OnColumnChanged;
public ISearchCriterion FilterOptionsValues { get; set; }
}
}
I figured it out. Here is my solution:
I modified the GetPostBackControl to look for not only the linkbutton that inserts the user control, but for controls that contain the id of child controls of the inserted user control(as to capture the OnSelectedIndexChanged that gets fired from inside my user control).
protected Control GetPostBackControl(System.Web.UI.Page page)
{
Control control = null;
string ctrlname = Page.Request.Params["__EVENTTARGET"];
if (ctrlname != null && ctrlname != String.Empty)
{
//if it contains options then it's a control inside my usercontrol
if (ctrlname.Split('$')[2].Contains("options"))
{
var c = new Control();
c.ID = ctrlname;
return c;
}
else
{
control = FindControlRecursive(page, ctrlname.Split('$')[2]);
}
}
else
{
string ctrlStr = String.Empty;
Control c = null;
foreach (string ctl in Page.Request.Form)
{
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
ctrlStr = ctl.Substring(0, ctl.Length - 2);
c = page.FindControl(ctrlStr);
}
else
{
c = page.FindControl(ctl);
}
if (c is System.Web.UI.WebControls.CheckBox ||
c is System.Web.UI.WebControls.CheckBoxList)
{
control = c;
break;
}
}
}
return control;
}
Then I modify the OnPreInit event to look for controls with an id of the linkbutton or an id that contains "options" :
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
System.Web.UI.MasterPage m = Master;
Control control = GetPostBackControl(this);
if (control != null)
{
if ((control.ClientID == (lbAddAndCondtion.ClientID) || createAgain) || control.ID.Contains("options"))
{
createAgain = true;
CreateUserControl(control.ID);
}
}
}
The critical fix was in the CreateUserControl method. In my original code I was trying to directly load the user control from my generic list that was stored in Session. I changed that to actually create a new instance of the user control, assign that new instance an id that matches the one stored in Session, and then add it to the placeholder:
protected void CreateUserControl(string controlID)
{
try
{
if (createAgain && phConditions != null)
{
if (OptionControls.Count > 0)
{
phConditions.Controls.Clear();
foreach (var c in OptionControls)
{
FilterOptionsCollectionView foc = new FilterOptionsCollectionView();
foc = Page.LoadControl("~/Views/FilterOptionsCollectionView.ascx") as FilterOptionsCollectionView;
foc.ID = c.ID;
phConditions.Controls.Add(foc);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
The only thing I changed in the user control was moving the method that loads my drop down lists's and wiring up the OnSelectedIndexChanged event into the OnInit event. Now I can dynamically load as many instances of the user control I want and all of the event's inside the user control fire correctly and state is persisted across postbacks!!
Hope this helps someone else!!

Resources