When this javascript function get called? - asp.net

I have created one page.In that page,I wrote one javascript function for displaying character count,when user enter something in textbox.
protected void Page_Load(Object sender, EventArgs e)
{
TextBox1.Attributes.Add("onkeyup", "DisplayCharCount()");
}
First time pageload,textbox is blank. Textbox does not have autopostback== true.After
pageload,user enter text into textbox.This time page is not loaded again.So when this function get called?

Page_Load will call everytime a page reloaded. so onkeyup will bind to the textbox everytime a page reloaded.
When this function get called?
This event is triggered when the user releases a Key while typing on TextBox1.
You can also bind it for the first time only:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
TextBox1.Attributes.Add("onkeyup", "DisplayCharCount()");
}
}
Or you can also bind it directly as:
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" onkeyup="DisplayCharCount()">
</asp:TextBox>

The Page_Load method is called every time a user requests the page. The DisplayCharCount method is called whenever a user pressed a key (that is, release the key) in the TextBox1 element.

Related

ASP:Button tag is onclick method is not calling

Button on click method is not calling
Button code :
<asp:Button ID="personalSub" runat="server" ValidationGroup="personal" Text="Save" CausesValidation="false" OnClick="InsertPersonalDetail" />
C# Code :
protected void InsertPersonalDetail(object sender, EventArgs e)
{
Console.WriteLine("hello");
MessageBox.Show("hello");
}
If you have any problem on the page then you must see a compiler error.
You do NOT have compiler error witch is means that asp.net finds the InsertPersonalDetail function on code behind.
From what I see you call inside the button click two functions that are for desktop programming (not for web page).
Neither one can have any visible effect on your click - there is no console there to see anything, neither user interface to open the MessageBox.
protected void InsertPersonalDetail(object sender, EventArgs e)
{
Console.WriteLine("hello"); // have no effect on web page
MessageBox.Show("hello"); // have no effect on web page
}
So its called but you don't see it by just wait a pop up to appears
To check this out, run it with debuger and add a break point there.
Or add a literal on page and add some text there to verify that is called.
eg, add on page
<asp:Literal runat="server" ID="txtLiteral" />
and on code behind
protected void InsertPersonalDetail(object sender, EventArgs e)
{
txtLiteral.Text += "InsertPersonalDetail called <br />";
}

How can I have a user control button behave differently on different aspx pages?

We have a user control that has a button. We use this user control on different aspx pages. We want the button to behave differently on different pages (dynamically). How might I achieve this goal?
It can be done using event in aspx.cs.
Suppose I have a button on user control
<asp:Button ID="btnClick" runat="server" Text="Click Me" onclick="btnClick_Click" />
on the user control code behind you can write as follows
public event EventHandler ButtonClickDemo;
protected void btnClick_Click(object sender, EventArgs e)
{
ButtonClickDemo(sender, e);
}
No on your aspx.cs content page you can use it as follows
protected void Page_Load(object sender, EventArgs e)
{
Demo1.ButtonClickDemo += new EventHandler(Demo1_ButtonClickDemo);
}
protected void Demo1_ButtonClickDemo(object sender, EventArgs e)
{
Response.Write("It's working");
}
Where Demo.ascx is the user control, so you can write Demo1.ButtonClickDemo
Depending upon how dynamic you want this functionality to be, it may be easier to simply create a property on your user control that would be set by your ASPx (if you can pass the information declaratively) or your codebehind (if you need to pass it programmatically). c.f. http://msdn.microsoft.com/en-us/library/26db8ysc.aspx for more information on creating user control properties.

Why ispostback not working with dropdown box

I want to keep selected item after page reload:
Excerpt from .aspx:
<asp:DropDownList ID="MyDropDown" runat="server" AutoPostBack="true"
onselectedindexchanged="MyDropDown_SelectedIndexChanged">
</asp:DropDownList>
Exerpt from .cs in page_load
if (!IsPostBack)
{
PopulateDropDownList();
}
with
private void PopulateDropDownList()
{
MyDropDown.Items.Add("1");
MyDropDown.Items.Add("2");
}
protected void MyDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect(Request.RawUrl);
}
Response.Redirect refresh the page and you will loose view state that will have selected index. You can put the selected index in session before redirecting.
protected void MyDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
Session["MyDropDownSelectedIndex"] = MyDropDown.SelectedIndex.ToString();
Response.Redirect(Request.RawUrl);
}
You need to populate the drop down list in the Page init event. If you do that during Page load event the view state cannot be restored correctly (because the drop down list is not populated before Page load event) so the on selected index changed event cannot be fired.
EDIT: you may want to cache the data which populate the drop down list to save some around trip to the database. I think you do not need to redirect in the on selected index changed event too.

Wiring events on dynamically-loaded ASP.NET User Controls?

For a "dashboard" module I need to dynamically load user controls based on criteria as the user enters the page (role, etc). The problem is that the events are not being fired at all from the controls
As I understand it I need to load the controls in the OnPreInit method of the dashboard page, however I cannot get a reference to the Placeholder control at this point of initialization (i.e. I get a NullReferenceException); trying to load the Placeholder dynamically via Page.FindControl gives me, ironically, a StackOverflowException.
I've tried loading the controls in PreRender and OnInit as well but the events in the controls are not wired up properly and will not fire.
The code is basically this:
// this does not work; if I try to access the placeholder control itself
// ("phDashboardControls") I get a NullReferenceException, if I try
// Page.FindControl("phDashboardControls") I get a StackOverflowException
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
Control ph = Page.FindControl("phDashBoardControls"); // Placeholder
if (ph != null)
{
// GetControlsToLoad just instantiates the controls and returns
// an IList<Control>. Eventually it will have logic to
// determine which control needs to be loaded based on user role etc.
foreach (Control control in GetControlsToLoad())
{
ph.Controls.Add(control);
}
}
}
// IModularControl is a custom interface defining a single
// Initialize method to set up a control...
private void Page_Load(object sender, EventArgs e)
{
foreach (Control control in this.phDashboardControls.Controls)
{
if (control is IModularControl)
((IModularControl)control).Initialize(this.CompanyID);
}
}
I've successfully loaded controls dynamically in Page_Load before. The only thing I found I had to be careful of was to ensure that if I did a postback, the same controls were loaded in subsequent page_load to ensure that the view state didn't get corrupted... all events etc worked as expected. In my case the controls flow ended up something like this:
page_load - load control a
(do something which causes postback and event x to fire)
page_load - make sure you load control a
event_x - clear control a, load control b
(do something which causes postback)
page_load - make sure you load control b
...
it meant loading controls you fully intented discarding, but was the only way I could find to not corrupt the viewstate...
If you have a page with PlaceHolder1 and Label1 in it, then the following code causes the button click event to fire just fine:
protected void Page_Load(object sender, EventArgs e)
{
var dynamicButton = new Button() { Text = "Click me" };
dynamicButton.Click +=new EventHandler(dynamicButton_Click);
PlaceHolder1.Controls.Add(dynamicButton);
}
void dynamicButton_Click(object sender, EventArgs e)
{
Label1.Text = "Clicked button";
}
Behaves the same with a user control:
WebUserControl ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Click Me" onclick="Button1_Click" />
WebUserControl code behind:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Clicked Button";
}
parent control that loads the child control:
protected void Page_Load(object sender, EventArgs e)
{
var dynamicControl = Page.LoadControl("~/WebUserControl.ascx");
PlaceHolder1.Controls.Add(dynamicControl);
}
Just FYI the issue had to do with validation; the events weren't firing properly because some of the validation controls (there were a ton) weren't configured to only apply to that control.

Raise ItemDataBound Event from Repeater Within User Control to Page

I have a user control that contains a repeater. We have added some paging and sorting into the user control and it all works well.
What I need now is a nice way to catch the OnItemDataBound event of the inner repeater and then bubble it up to be accessible directly from the user control from within the page.
We have tried catching it and then declaring it in the user control but it just won't work. Has anyone ever tried this before and if so could I see some code to suggest how it might look.
Many Thanks
Try something like this:
<asp:Repeater ID="Repeater1" runat="server"
onitemdatabound="Repeater1_ItemDataBound">
</asp:Repeater>
Then subscribe to the event, and publish another event with the same data
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
OnInnerRepeaterItemDataBound(sender,e);
}
public event EventHandler<RepeaterItemEventArgs> InnerRepeaterItemDataBound;
public void OnInnerRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (InnerRepeaterItemDataBound != null)
InnerRepeaterItemDataBound(sender, e);
}
That should do it, now you can subscribe to the user control Event InnerRepeaterItemDataBound that would be fired when your inner Repeater1_ItemDataBound fire.

Resources