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

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.

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());

How to set a asp:DropDownList SelectedValue to a Session Variable?

There are several articles describing how to do this is code behind however:
Is it possible to set the value of a dropdownlist to a session variable on the aspx page?
I am using SqlDataSource to populate the dropdownlist so do not wish to add code behind if it can be avoided.
<asp:DropDownList ID="ddl" runat="Server" DataSourceID="sqlDS" DataValueField="ID" DataTextField="TEXT" AppendDataBoundItems="true">
<asp:ListItem Text="" Value="" Selected="True" />
</asp:DropDownList>
<asp:SqlDataSource ID="sqlDS" runat="Server" SelectCommand="spDS" SelectCommandType="StoredProcedure" />
Set Session("ID") as selected value on load?
The dropdown list is already populated from the sqldatasource. I just want to set the initial value on page load.
You need a server side code in order to use Session. The following code doesn't requires code behind file, but again the code inside script will run at server side.
<asp:DropDownList ID="ddl" runat="Server"
DataSourceID="sqlDS"
DataValueField="ID"
DataTextField="TEXT"
AppendDataBoundItems="true"
OnSelectedIndexChanged="ddl_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem Text="" Value="" Selected="True" />
</asp:DropDownList>
<asp:SqlDataSource ID="sqlDS" runat="Server"
SelectCommand="spDS" SelectCommandType="StoredProcedure" />
<script runat="server">
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Session["SelecteValue"] = ddl.SelectedValue;
}
</script>
Note: Make sure AutoPostBack="True" for DropDownList.
Do not mix code with markup. It makes sense to separate them for many reasons. So ASPX will have just the presentation, and CS/VB just the code logic.
When you compile/deploy your side to production - there will not be "the second page" - only ASPX page will remain. Code will be compiled into a DLL.
you'll need an event for your dropdown list on change. Are you using C# or VB.net for your codebehind?
add to onSelectedIndexChanged="ddl_OnSelectedIndexChanged"
to your code behind add:
{this is C# vb is similar}
protected void ddl_OnSelectedIndexChanged(Object sender, EventArgs e)
{
Session["selectedID"] = ddl.selectedValue;
}
to your page load, add
if (isPostback)
{
ddl.selectedValue = Session["selectedID"];
}

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.

How can I create an ASP.NET AJAX UpdatePanel that refreshes a Repeater when a DropdownList control has the Selected Item changed?

I have a simple problem. I have a dropdown list and a databound repeater. When the user changes the selection in the dropdown list I would like to reload the repeater. I would like to use ASP.NET AJAX so that this does not refresh the entire page. I have read the ASP.NET AJAX documentation over and over but can not find a clear explanation of how to do this. Here is part of my ASPX page
<asp:ScriptManager id="smScriptManager" runat="server" />
<asp:DropDownList id="ddlLocations" runat="server" AutoPostback="true" OnSelectedIndexChanged="ddlLocations_SelectedIndexChanged">
<asp:ListItem Text="Location 1" Value="1"></asp:ListItem>
<asp:ListItem Text="Location 2" Value="2"></asp:ListItem>
<asp:ListItem Text="Location 2" Value="3"></asp:ListItem>
</asp:DropDownList>
<asp:UpdatePanel id="upUpdatePanel" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlLocations" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:Repeater id="rptItems" runat="server">
<ItemTemplate>
... data bound fields for each location go here ...
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
In my code behind I have a separate data binding function that binds the repeater. Currently I call it on Page Load only if Page.IsPostBack = false. So the page loads fine the first time and the Repeater is loaded with all of the data for Location 1 (since it is selected). I also have code in the "ddlLocations_OnSelectedIndexChanged" function that calls the data binding function. In fact, if I strip out all of the AJAX/UpdatePanel stuff the page works fine (although it does a complete page refresh).
With the AJAX stuff, when the user selects Location 2 or Location 3 I get the following JS error:
Message: Sys.WebForms.PageRequestManagerServerErrorException: StartIndex cannot be less than zero.
Parameter name: startIndex
Line: 4723
Char: 21
Code: 0
URI: http://localhost/ScriptResource.axd?d=sTWt9V9Pb7V99ft1kYaE90l3bO7maFff4srx6ham1O6ideYDjPbZU5dv5QJjmzBCPxFQIGrdN2PIuOG7y3evLrZF4ETSZ2de6iwiLo9yZ4w0RvtADl-5JZXm0C_1eyn2F6p6fNX5ZDkxi6yJHF0czKc2lWjUlRrkShaVa4T1l8BPah6A0&t=ffffffff9bdfdd38
Anyone have any ideas why this is happening? Am I doing something wrong? I feel like I don't quite understand how the UpdatePanel works. I get the feeling that I should first set up the page to work without the UpdatePanel/AJAX stuff (and do a complete page refresh). Then add in the UpdatePanel/AJAX stuff and somehow the code magically figures out that I just want the updated Repeater HTML. Or something like that. Any ideas?
UPDATE:
Here is how my back end code works
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
this.BindData();
}
}
protected void BindData()
{
this.BindDropDownList();
this.BindRepeater();
}
protected void BindDropDownList()
{
...call code for binding drop down list...
(ddlLocations is actually databound - I simplified it above for purposes of this post)
}
protected void BindRepeater()
{
...call code for binding the repeater...
}
protected void ddlLocations_SelectedIndexChanged(object sender, EventArgs e)
{
this.BindRepeater();
}
Thanks,
Corey

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