How can I create an EventHandler inside an EventHandler - asp.net

I have some code which involves dynamically creating new buttons, when a user clicks on a particular button. However the EventHandlers defined for these dynamically created buttons do not execute when I click on any one of them. Here is the errant code snippet:
protected void Page_Load(object sender, EventArgs e)
{
.......
btn1.Click += new EventHandler(this.btn1_Click);
.......
}
protected void btn1_Click(object sender, EventArgs e)
{
.......
LinkButton btn2 = new LinkButton();
btn2.Click += new EventHandler(this.btn2_Click);
.........
}
protected void btn2_Click(object sender, EventArgs e)
{
.......
}
The code execution never enters btn2_Click(). Am I doing something wrong here?

Try declare LinkButton btn2 as global variable and and wire the event btn2.Click += new EventHandler(this.btn2_Click) as the controls are created.

btn2 disappears as soon as you leave the btn1 event handler. It's a local variable, and goes away as soon as it's out of scope.
Did you ever see the second button? Did you click on it? If so, then you clicked on the wrong button. This one you added never appeared on your page.
In order for a control to become visible (and to render into HTML), it must be placed inside of the Controls collection of a visible control. You're not doing anything with it.

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")
{
...
}
...
}

how to disable a pageload property under certain circumstances

In .NET i have a gridview which has to display on the mainpage with default settings. So i put it in pageload code. In the same page i have a "List" button; people choose date etc. and when they press the button gridview loads data from another stored procedure. I put that code under List button event. But after people press List button and gridview comes with the needed data, if they press something else (because of page refresh itself) gridview turns back to default settings.
How do i keep the gridview with wanted data?
protected void Page_Load(object sender, EventArgs e)
{
opsbelgegridview.DataSource = DB.OpsHavuzGetir();
opsbelgegridview.DataBind();
protected void listelebtn_Click(object sender, EventArgs e)
{
opsbelgegridview.DataSource = DB.OpsHavuzDetayListeleBtn(tarih1.ToString("yyyy-MM-dd"), tarih2.ToString("yyyy-MM-dd"), durumdd.SelectedItem.Text.ToString(), islemtipdd.SelectedItem.Text.ToString());
opsbelgegridview.DataBind();
You can use IsPostBack() and only load the initial grid on the first load of the page. Then if the grid data changes it will stay.
private void Page_Load()
{
if (!IsPostBack)
{
opsbelgegridview.DataSource = DB.OpsHavuzGetir();
opsbelgegridview.DataBind();
}
}

How to display gif while GridView Process ASP.NET

I have an application that displays various data in an ASP.NET GridView. The values ​​are displayed as a selection of combobox. When I select comobo box, the reload process is taking about 8 seconds. I would like to display a gif of load before starting the process and end it cancel the display image. I tried to use a thread for this, but it did not work very well. Could someone help me?
protected void Page_Load(object sender, EventArgs e)
{
//My Image
imageLoad.Visible = true;
Assembly myAsm = Assembly.Load("PainelBordo");
AssemblyName aName = myAsm.GetName();
Version version = aName.Version;
BusinessLogicLayer bll = new BusinessLogicLayer();
LoadDDLWRTG(CreateDataTableWRTGList());
LoadDataPBList();
TimerRefresh.Interval = Convert.ToInt32(ConfigurationManager.AppSettings["TimerInterval"].ToString());
lblUpdateDate.Text = "Refresh " + bll.DateUpdateFormat(DateTime.Now);
// My image
imageLoad.Visible = false;
}
Combobox SelectedIndexChanged.
protected void ddlWRTGroup_SelectedIndexChanged(object sender, EventArgs e)
{
Page_Load(sender, e);
}
Drag and drop a Button(btnInvoke) and Label(lblText) control inside the UpdatePanel. Also add a <div id="divImage"> inside the UpdatePanel. This div will contain a .gif image that depicts progress and is initially set to invisible style="display:none". On the button click, perform a time consuming task. In our case, we have set a delay of 3 seconds by using Thread.Sleep(3000)
C#
protected void btnInvoke_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(3000);
lblText.Text = "Processing completed";
}
Took from here

ASP.NET Button on Placeholder and Placeholder in an User Control (ascx) file Button event not fired

I am dynamically creating link buttons on user control using a place holder and the eventhandler attached to the link button click+=new Event(Button_Click) is not firing
Thanks in Advance
Code Snippet of
protected override void OnInit(EventArgs e)
MenuListPlaceHolder.Controls.Add(new LiteralControl("<li>"));
ctrl.ID = this.UniqueID + (nCounter++).ToString();
ctrl.Text = cardType.Name;
ctrl.Click += new EventHandler(this.CardName_Click);
MenuListPlaceHolder.Controls.Add(ctrl);
MenuListPlaceHolder.Controls.Add(new LiteralControl("</li>"));
When clicked post back event is fired but not executing CardName_Click
You have to attach it on Page_Load event
like so:
protected void Page_Load(object sender, EventArgs e) {
this.Btn.OnClick+=new Event(Button_Click)
}
you should check it: here to learn about page cycle

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