Getting control that fired postback in page_init - asp.net

I have a gridview that includes dynamically created dropdownlist. When changing the dropdown values and doing a mass update on the grid (btnUpdate.click), I have to create the controls in the page init so they will be available to the viewstate. However, I have several other buttons that also cause a postback and I don't want to create the controls in the page init, but rather later in the button click events.
How can I tell which control fired the postback while in page_init? __EVENTTARGET = "" and request.params("btnUpdate") is nothing

It is possible to determine which control caused a PostBack by looking at Request.Form["__EVENTTARGET"]. The problem with this is that button ids will not show unless you set their UseSubmitBehavior to false. Here's an example:
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
switch (Request.Form["__EVENTTARGET"].ToString())
{
case "ddlOne":
break;
case "btnOne":
break;
case "btnTwo":
break;
}
}
}
.aspx
<form id="form1" runat="server">
<asp:DropDownList ID="ddlOne" AutoPostBack="true" runat="server">
<asp:ListItem Text="One" Value="One" />
<asp:ListItem Text="Two" Value="Two" />
</asp:DropDownList>
<asp:Button ID="btnOne" Text="One" UseSubmitBehavior="false" runat="server" />
<asp:Button ID="btnTwo" Text="Two" UseSubmitBehavior="false" runat="server" />
</form>

Related

AutoPostBack and parameter value after browser Back

When using postback and then browser Back button, previous content is shown correctly, but the parameter that triggered postback has the latest value - it is not returned to the value it had before it triggered postback. This creates an invalid state.
In the example, dropdown has AutoPostBack set to true.
After I type "a2" and change dropdown value to "text2":
After I type "a3" and change dropdown value to "text3":
After Back:
Turning of browser cache programmatically didn't help, as it gives "Document Expired" on browser Back action.
After going Back, I wish that parameters match the content which is generated with those parameters, specifically the ones that are AutoPostBack. Is there a desired way of getting that behavior?
Code:
aspx
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text3" />
</asp:DropDownList>
<div>Server content - <asp:Label ID="ServerContent" runat="server" /> </div>
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
ServerContent.Text = string.Format(
"received values: {0}, {1}", TextBox1.Text, DropDownList1.SelectedValue);
}
It is still not very clear what you are trying to do. The DropDownList changes, the server does a form post, you get a response and then you want that response in the previous state (before form post)? Seems like a weird rquirement. If a user goes back because he made a mistake, he changes the value and then does a PostBack again. No harm done.
But if you really want to set the value to it's default, you need to set the value of the DropDownList with JavaScript when the page has not done a PostBack. Take a look at my snippet below, it gives the desired results. It sets the SelectedIndex at 2 when the page is loaded, but does not when a PostBack is performed so the new value is still visible. Now when the user goes back the script is still present and will set the DropDownList to it's default value again.
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="aaa" Value="aaa"></asp:ListItem>
<asp:ListItem Text="bbb" Value="bbb"></asp:ListItem>
<asp:ListItem Text="ccc" Value="ccc"></asp:ListItem>
</asp:DropDownList>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setValue", "document.getElementById('" + DropDownList1.ClientID + "').selectedIndex = 2;", true);
}
}
I had to keep values for certain fields in additional hidden fields and use them on the client. The same example with "solution":
aspx
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text3" />
</asp:DropDownList>
<asp:HiddenField runat="server" ID="DropDownList1ValueCarrier" ClientIDMode="Static" />
<div>Server content - <asp:Label ID="ServerContent" runat="server" /> </div>
aspx.cs
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
DropDownList1ValueCarrier.Value = DropDownList1.Text;
}
js
$('#DropDownList1').val($('#DropDownList1ValueCarrier').val());

Asp.net C# - checkbox control won't stay true after code-behind runs

Front HTML
<asp:CheckBox ID="chkSend" runat="server" Text="Send?" />
The code that triggers the code behind
<asp:DropDownList ID="ddlStatus" OnSelectedIndexChanged="ddlStatus_SelectedIndexChanged" AutoPostBack="true"
runat="server" DataValueField="Id" DataTextField="Status" />
The code that runs in the code behind
protected void ddlStatus_SelectedIndexChanged(object s, EventArgs e)
{
this.chkSend.Checked = True;
}
When get back to the front end , the checkbox isn't checked. Any Ideas?
If it helps, this particular view is using Multi-views to which I'm new to.

Load another web page based on value of drop down list in asp.net

I am trying to redirect to another web page when the user selects the drop down list and the user should be redirected to another web page as soon as the user clicks the submit button.This is my code for drop down list and button.On clicking the "click to proceed" button the user should be taken to next web page depending on list selection.
Iam new to .Net Please help thanks in advance !!
<asp:DropDownList ID="DropDownList1" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="-1">Select User</asp:ListItem>
<asp:ListItem Value="staff">Staff</asp:ListItem>
<asp:ListItem Value="student">Student</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Click to Proceed" />
In your Button1_Click event, use the Response.Redirect method to send people to the appropriate page.
http://msdn.microsoft.com/en-us/library/a8wa7sdt%28v=vs.110%29.aspx
Following can be helpful for you.
protected void Button1_Click(object sender, EventArgs e)
{
string sel_val = DropDownList1.SelectedValue; // use sel_val to apply if, else logic to redirect to
// some possible examples
if (sel_val != "-1") // as SelectedValue is string
{
// assuming there is staff.aspx, and you want to redirect to that page on selecting staff, this is just an example
Response.Redirect(sel_val + ".aspx"); // use this to redirect to required page
}
}
Also change aspx code like this.Note i have changed OnClick from onclick.
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Click to Proceed" />

How do I load two ASP.NET UserControls on Demand?

I want load two user controls on demand.
asp:UpdatePanel ID="UpdatePanel1" runat="server"
ContentTemplate
asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false"
OnClick="Button1_Click" /
div id='Div_UserControlPlace' enableviewstate="true" runat="server"
/div
/ContentTemplate
Triggers
asp:PostBackTrigger ControlID="Button1" /
/Triggers
/asp:UpdatePanel
asp:UpdatePanel ID="UpdatePanel2" runat="server"
ContentTemplate
asp:Button ID="Button2" runat="server" Text="Button" UseSubmitBehavior="false"
OnClick="Button2_Click" /
div id='Div_UserControlPlace2' enableviewstate="true" runat="server"
/div
/ContentTemplate
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Control FeaturedProductUserControl = new Control();
FeaturedProductUserControl = LoadControl("WebUserControl1.ascx");
FeaturedProductUserControl.EnableViewState = true;
Div_UserControlPlace.Controls.Add(FeaturedProductUserControl);
}
protected void Button2_Click(object sender, EventArgs e)
{
Control FeaturedProductUserControl2 = new Control();
FeaturedProductUserControl2 = LoadControl("WebUserControl2.ascx");
FeaturedProductUserControl2.EnableViewState = true;
Div_UserControlPlace2.Controls.Add(FeaturedProductUserControl2);
}
I load the first user control by clicking on the first button - this works properly but when I click on the other button to load the second UserControl, the first UserControl disappears and the second UserControl loads.
Thanks
IFA_User
You should use the Placeholder control to dynamically add your controls to the form.
Take a look at my last responses about dynamic controls:
OnClick event of dynamically created LinkButtons is not working
Dynamically Added DropDownlists Are Not Firing SelectedIndexChanged Event
Dynamically create an ImageButton
Now I already have some code working for demo purpose, each dynamic user controls keeps its state across post backs
This is the output:
ASPX
<asp:PlaceHolder runat="server" ID="addresses" /><br />
<asp:Button Text="Add Address" runat="server" ID="addAddress" OnClick="addAddress_Click" />
ASPX Code behind
protected void Page_PreLoad(object sender, EventArgs e)
{
for (int i = 0; i < this.DynamicControlsCount; i++)
{
var c = this.LoadControl("~/AddressControl.ascx");
this.addresses.Controls.Add(c);
}
}
protected void addAddress_Click(object sender, EventArgs e)
{
this.DynamicControlsCount++;
var c = this.LoadControl("~/AddressControl.ascx");
this.addresses.Controls.Add(c);
}
protected int DynamicControlsCount
{
get
{
if (this.ViewState["ac"] == null)
{
return 0;
}
return (int)this.ViewState["ac"];
}
set
{
this.ViewState["ac"] = value;
}
}
ASCX
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AddressControl.ascx.cs" Inherits="WebApplication1.AddressControl" %>
<asp:Panel ID="Panel1" runat="server" GroupingText="Address" DefaultButton="btnSave">
Street: <asp:TextBox runat="server" ID="txtStreet" /><br />
City: <asp:TextBox runat="server" ID="txtCity" /><br />
<asp:Button Text="Save" runat="server" ID="btnSave" OnClick="btnSave_Click" />
</asp:Panel>
<asp:Panel runat="server" GroupingText="Address Summary" Visible="false" ID="summary">
<asp:Label ID="lblStreet" runat="server" /><br />
<asp:Label ID="lblCity" runat="server" />
</asp:Panel>
ASCX Code behind
protected void btnSave_Click(object sender, EventArgs e)
{
this.summary.Visible = true;
this.lblCity.Text = "Selected city: " + this.txtCity.Text;
this.lblStreet.Text = "Selected street: " + this.txtStreet.Text;
}
When a user control is created in the HTML, asp.net will persist across postbacks without any user interaction. But if you are loading them programatically (dynamically), they will not persist accross postbacks. So if you load them programmatically, you have the added task of persisting them programmatically as well. Use the ViewState (or Session I suppose) to store what has been loaded and perhaps any other necessary information that needs to be loaded between postbacks. Every single postback will require you to reload every control or else they will disappear.
There are couple of ways of doing it:
U can load the UserControls using Ajax. Benefit of using Ajax, is ur page does not get post back, thus for example, on click event of Button1, call a ajax(traditional/Jquery) to load UserControl1, and on button click of Button2 User control2.
Put the two button in two different updated panel, by doing this the click event will only refresh a part of ur page.
U have to save somewhere (ViewState/Session),which buttons are clicked, and upon clicking of any button check the value of that variable, and explicit load the control.
Points to note - If u want to get ur data back when ur page made a complete postback, then u have to add the controls keeping in mind the Page load event cycle.

ASP.NET - Using checkbox from the calender control

I am implementing a leave system using the calender control. Something like below :-
Following is the markup :-
<asp:Calendar ID="Calendar1" runat="server" ondayrender="Calendar1_DayRender"
ShowGridLines="True">
</asp:Calendar>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="vacation" Text="Vacation" />
<asp:ListItem Value="sick" Text="Sick" />
<asp:ListItem Value="training" Text="Training" />
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
Following is the code-behind :-
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (!e.Day.IsOtherMonth && !e.Day.IsWeekend)
{
CheckBoxList list = new CheckBoxList();
list.Items.Add(new ListItem("Half day"));
list.Items.Add(new ListItem("Full day"));
e.Cell.Controls.Add(list);
}
}
However, I am not able to access the the checkbox values neither in the button_click event nor in the DayRender event? Could anybody help? Is there a better way to implement this?
Because you are not binding any event handler to the CheckBox's also you haven't shown us the java-script you are using for Button click so I assume that you instead wanted to run a Server side code instead of Client side java-script. So instead of using OnClick attribute which is for client event script you should use Click Event which is for server side code

Resources