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.
Related
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
}
}
this is a two part problem, one is with CSS and the other with codebehind..
Here is my navigation code for my buttons...
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Buttons/upviewassets.png" OnClick="ImageButton1_Click" />
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/Buttons/upaddassets.png" OnClick="ImageButton2_Click" />
All the buttons are side by side. On the OnClick() event my code is this...
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
ImageButton1.ImageUrl = "Buttons/dnviewassets.png";
ImageButton2.ImageUrl = "Buttons/upaddassets.png";
//Response.Redirect("~/WebForm1.aspx");
}
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
ImageButton1.ImageUrl = "Buttons/upviewassets.png";
ImageButton2.ImageUrl = "Buttons/dnaddassets.png";
//Response.Redirect("~/WebForm1.aspx");
}
When i comment out the response.redirect it works, but i need to be able to use the response.redirect because this is in a masterpage and i need these buttons to redirect to other pages, when I run it with the response.redirect method the images don't change. As well, when i first run it without the response.redirect, when i click on the button it jumps quickly and goes back to where it should be, but then works fine everytime after.
So for the second part, I have also tried using css to change the imagebuttons image but couldn't get it to work, and i have searched online and went through tutorials but even when using the code provided it didn't work properly and my buttons kept jumping.
I'm trying to mimic a look of tabs in the master page.
Thanks
I would save a flag in the session in click event and retrieve it in redirected page PreRender:
protected override void OnPreRender(EventArgs e)
{
if (!IsPostBack)
{
PaintButtons();
}
base.OnPreRender(e);
}
And my PaintButtons method:
private void PaintButtons()
{
if(Session["ImageButton_Toggled"] == null )
{
ImageButton1.ImageUrl = "Buttons/upviewassets.png";
ImageButton2.ImageUrl = "Buttons/upaddassets.png";
}
else
{
int toggleId = 1;
int.TryParse(Session["ImageButton_Toggled"].ToString(), out toggleId);
if (toggleId == 1)
{
ImageButton1.ImageUrl = "Buttons/dnviewassets.png";
ImageButton2.ImageUrl = "Buttons/upaddassets.png";
}
else
{
ImageButton1.ImageUrl = "Buttons/upviewassets.png";
ImageButton2.ImageUrl = "Buttons/dnaddassets.png";
}
}
}
Click event methods in my masterpage:
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Session["ImageButton_Toggled"] = 1;
Response.Redirect("~/WebForm1.aspx");
}
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
Session["ImageButton_Toggled"] = 2;
Response.Redirect("~/WebForm1.aspx");
}
Now I can redirect to any page I want, and my masterpage will work as expected.
I wrote this code in .NET. When I want to change ‘s’ by clicking button2, it doesn’t change. I mean after clicking button2 and then I click Button1 to see the changes but nothing changes. How can I change and access the value of ‘s’ properly. What am I doing wrong?
public string s;
public void Button1_Click(object sender, EventArgs e)
{
Label1.Text = s;
}
public void Button2_Click(object sender, EventArgs e)
{
s = TextBox1.Text;
}
You need to understand how web applications work.
In each post back an instance of the class that handles the page is loaded, so when you click on button 1, the page does a post back and loads again, so this way the variable s isn't loaded with your content.
To make this code work, you need to save the S values on the page viewstate.
try replacing "public string s;" with this:
public string s
{
get { return (string)ViewState["myValue"]; }
set [ ViewState["myValue"] = value };
}
More Information about Page Life Cycle at: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx
I have a fairly simple web application that gets a list of items from a database (in a DataTable), and binds a view of that DataTable to a Repeater.
When converting my DataTable to a List (which is done in a class library), Page Load fires a second time! Walking though the debugger, the same items are in the list that were in the DataTable.
The only code in my page was:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rptOffers.DataSource = DataAccess.GetOfferList(offerId); // returns List<T>
rptOffers.DataBind();
}
}
public static List<OfferItem> GetOfferList(int offerId)
{
DataTable dtOffers = GetOfferData(offerId);
List<OfferItem> offers = new List<OfferItem>();
// loop throw all of the offers
foreach (DataRow dr in dtOffers.Rows)
{
// add each offer to the List<>
OfferItem currentOffer = new OfferItem();
// initialize the OfferItem properties...
offers.Add(currentOffer);
}
return offers;
}
When I change it back to this, it works fine:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rptOffers.DataSource = DataAccess.GetOfferItems(offerId);
rptOffers.DataBind();
}
}
Is there anything else I need to do in my List to keep it from running Page Load again?
I have experienced this issue when AutoEventWireup is set to true in my .aspx file
<%# ... AutoEventWireup="True" ... %>
and my InitializeComponent function still contains a hookup for Page_Load
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
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)