Asp.net page - user control communication - asp.net

I have a page Product.aspx,there I have a user control ProductDisplay.ascx which has been created by drag and drop.
Now when a button is clicked in ProductDisplay.ascx,I want a logging function to be called which is in Product.aspx.
To achieve this I have used delegates
on ProductDisplay.ascx
public delegate void LogUserActivity(ProductService objService);
public event LogUserActivity ActivityLog;
on Product.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ProductDisp.ActivityLog += new User_UserControl_ProductDisplayBox.LogUserActivity(LogProduct);
}
}
Now button click event of ProductDisplay.ascx
protected void imgBtnBuyNow_Click(object sender, ImageClickEventArgs e)
{
if (ActivityLog != null)
{
ActivityLog(Product);
}
Response.Redirect("~/User/ShoppingCart.aspx");
}
My problem is that whenever i click this button ActivityLog is null.Why is it null?
My idea is that once i click this button,page posts back and its previous state is lost.
Please help me out with a reason and solution.
Secondly,I want to do away with null checking
**if (ActivityLog != null)**
{
ActivityLog(Product);
}
I saw some code which instantiates a delegate with a default value the moment it is declared,but i was not able to find it.Please help.

I have found solution to first problem
if (!IsPostBack)
{
ProductDisp.ActivityLog += new User_UserControl_ProductDisplayBox.LogUserActivity(LogProduct);
}
This was causing the issue.Move this line
ProductDisp.ActivityLog += new User_UserControl_ProductDisplayBox.LogUserActivity(LogProduct);
out of if (!IsPostBack)

Related

How to update CheckBoxes on the client side after making changes on the server side?

I have a DropDownList and a CheckBox on my web form. After the DropDownList is clicked and this event is posted back to the server. DropDownList_SelectedIndexChanged event is called on the server side. Inside that event handler, I have CheckBox.Checked = true, But I couldn't make the page on the client side to reflect this change (CheckBox.Checked = true). How do I achieve this? Or am I in the wrong direction to use the DropDownList's event handler to update the CheckBox because the page firstly reloads and then DropDownList_SelectedIndexChanged is called?
Page load method:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.DropDownList1.Items.Clear();
AddItemsToDropDownList();
}
}
DropDownList selected index changed event handler:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var selected = this.DropDownList1.SelectedItem.Text;
CheckBox checkBox = GetCheckBoxToBeSetByText(selected);
checkBox.Checked = true;
}
OK. Found the issue. Actually there is nothing wrong with the code in my original post. But to make a smallest sample when I posted, I removed some "extra" code. The below is the "complete" code (OK, fine, I still removed some code). As you can see, I put the CheckBox into a static Dictionary. Each time the SelectedIndexChanged event handler is called, it's modifying the CheckBox in that static Dictionary, which means it's modifying the CheckBox object created from the last session? (still not clear here) Looks like each time when a postback message is received, a new set of CheckBox objects are created. Bear with me if this is known to everybody here already because I only have two days of experience on this web development thing up to today.
private static Dictionary<Environment, CheckBox> EnvironmentsCheckBoxes;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
EnvironmentsCheckBoxes = new Dictionary<Environment,CheckBox>();
EnvironmentsCheckBoxes.Add(Environment.Dev1, this.Dev1_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.Dev2, this.Dev2_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.QA, this.QA_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.QA2, this.QA2_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.Demo, this.Demo_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.Prod, this.Prod_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.UAT, this.UAT_CheckBox);
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var selected = this.DropDownList1.SelectedItem.Text;
if (selected == "Dev1")
{
EnvironmentsCheckBoxes[Environment.Dev1].Checked = true;
}
else if (selected == "Dev2")
{
...
}
...
}

Validation in different Tabs of windows form using ErrorProviders

I am working on a windows Forms Application and trying to validate few textboxes using errorproviders but the problem is when I am clicking on a button present in Tab 1, all the textboxes even present on a different tabs gets validated. I want the validation to occur for textboxes present on the current tab and not on any control present on any other tab. How can I achieve this? Please help. Below is the code related to validation in the click event.
private void btnCreateUser_Click(object sender, EventArgs e)
{
if (this.ValidateChildren(ValidationConstraints.Enabled))
{
// Some Code here
}
}
Below is code used for validating and validated event for one textbox. I am using similar code for other textboxes as well present on other tabs.
private void txtFirstNm_Validating(object sender, CancelEventArgs e)
{
bool cancel = false;
if (txtFirstNm.Text.Trim().Length == 0)
{
cancel = true;
errorProvider1.SetError(txtFirstNm,"Please enter First Name");
}
else
{
cancel = false;
errorProvider1.SetError(txtFirstNm, "");
}
e.Cancel = cancel;
}
private void txtFirstNm_Validated(object sender, EventArgs e)
{
errorProvider1.SetError(txtFirstNm,"");
}
The Scenario that is given in my question can be handled by using below code. We can use the ValidationConstraint as Visible and this will make sure that Validation occurs on the Current visible Controls.
private void btnCreateUser_Click(object sender, EventArgs e)
{
if (this.ValidateChildren(ValidationConstraints.Visible))
{
// Some Code here
}
}

How to know the previous event handled in asp.net

on page load i have shown data from database onto a gridview(with edit and delete option). I also have a search button on the page. when i click on search the searched data should be visible in the gridview, which is working fine. But when i click on delete link after search it does not take the searched row. The page postsback after clicking on delete. I need to check the event performed prior to event performed on gridview. How to do that?? I hope that the issue is clear.. Any help is appreciated. Thanks.
Page_Load occurs before RowCommand, are you only binding grid if(!IsPostBack) ?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}
protected void SearchButton_Click(object sender, EventArgs e)
{
BindGrid(searchText.Text);
}
protected void GridView_RowCommand(object sender, GridViewRowEventArgs e)
{
switch(e.CommandName)
{
case "Delete":
DeleteRow(e.Row.CommandArgument);
break;
}
}
private void BindGrid()
{
//GridView binding business logic.
}
private void BindGrid(String searchTerm)
{
//GridView binding logic with searchTerm.
}
private void DeleteRow(String commandArg)
{
//Convert command arg to ID or whatever and delete data.
}

asp.net built runtime Menu with offsite link

I hope you can help me. First, I'd like to tell you I am a desktop app guy, which means I mostly develop my apps in desktop. Now I am trying to build some web app but it leads me to am not sure if confusion or just am doing it wrong.
I have a code here that it populates a menu at runtime. Runtime because they the menu items are populated at code behind and the items are fetched in database.
here's the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Menus menu = new Menus();
imgMainLogo.ImageUrl = VARIABLES.MainLogoImage;
menu.PopulateMenuControl(ref mainmenu, 2);
menu.PopulateMenuControl(ref footermenu, 9);
}
else
{
System.Diagnostics.Debug.WriteLine("link: " + footermenu.SelectedValue);
if (footermenu.SelectedValue != null)
{
Response.Redirect(footermenu.SelectedValue, true);
}
}
}
and the code in PopulateMenuControl
public void PopulateMenuControl(ref Menu menucontrol, int menuparentid)
{
//menucontrol.Items.Clear();
foreach (MenuFields mf in GetMenusByParentID(menuparentid))
{
MenuItem menuitem = new MenuItem(mf.MenuName, ReplaceSystemNameLink(mf.Link));
menucontrol.Items.Add(menuitem);
foreach (MenuFields cmf in GetMenusByParentID(mf.MenuID))
{
MenuItem childmenuitem = new MenuItem(cmf.MenuName, ReplaceSystemNameLink(cmf.Link));
menuitem.ChildItems.Add(childmenuitem);
}
}
}
So Page.IsPostBack is the very basic thing I should learn when doing something in a page. But the problem here is, one of my menu item in "footermenu" has an offsite link, and it should redirect the page into my blog.. but what's happening was, footermenu.SelectedValue is empty once I clicked on the "Blog" link.
What's going on?
UPDATE
I have updated the code still stuck, the SelectedValue is still empty
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Page_Load IsPostBack: " + Page.IsPostBack.ToString());
if (Page.IsPostBack)
{
if(footermenu.SelectedValue != null)
{
System.Diagnostics.Debug.WriteLine("link: " + footermenu.SelectedValue);
}
}
}
protected void Page_Init(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Page_Init IsPostBack: " + Page.IsPostBack.ToString());
if (!Page.IsPostBack)
{
Menus menu = new Menus();
imgMainLogo.ImageUrl = VARIABLES.MainLogoImage;
menu.PopulateMenuControl(ref mainmenu, 2);
menu.PopulateMenuControl(ref footermenu, 9);
}
}
You need to learn about the page lifecycle.
With dynamic controls (created and added in code), you need to re-create them on every page load - this is best done in the init event handler.

Handle Button Click Event from User Control loaded dynamically

I have a blank user control (child) and during Page_Load i create some text boxes and a button. I also add an event to the button.
I then load that user control dynamically from a placeholder in another usercontrol (parent).
Both controls are rendered correctly but when i click on the button, the event isnt fired.
Any ideas on how to handle the event?
Child code:
protected void Page_Load(object sender, EventArgs e)
{
/*... other user controls ..*/
UpdateButton = new LinkButton();
UpdateButton.ID = "buttonid";
UpdateButton.Text = "text";
UpdateButton.Click += new EventHandler(UpdateButton_Click);
this.Controls.Add(UpdateButton);
}
protected override void Render(HtmlTextWriter writer)
{
for (int i = 0; i < this.Controls.Count; i++)
{
this.Controls[i].RenderControl(writer);
}
}
public void UpdateButton_Click(object sender, EventArgs e)
{
//Do stuff
}
Parent code:
protected void Page_Load(object sender, EventArgs e)
{
placeholder.Controls.Clear();
ChildControl uc = (ChildControl)LoadControl("~/UserControls/ChildControl.ascx");
placeholder.Controls.Add(uc);
}
If i use the child control directy (ie without the parent the control) the click event is raised and handled nicely. But when i use the parent control, the debugger wont even hit a breakpoint inside UpdateButton_Click().
Thanks in advance.
I think I know what might be happening. In your parent Page_Load you are calling placeholder.Controls.Clear(); This does what you would imagine and clears the control, including any events that have occurred. What happens when remove this line? Do you get an additional one created on each postback?

Resources