SelectedIndexChange Not Firing Correctly - c#

I'm hoping someone can help me as I'm beating my head against a wall trying to figure out the problem. I have a databound CheckboxList that has the SelectedIndexChanged event wired up. AutoPostBack is equal to true and ViewStateMode and EnableViewState are set to "Enabled" and "True" respectively. I have other controls on this same page with server side events that fire just fine with no issue.
The weird thing is, the event SEEMS to be firing, as I can see the page reload when I check one of the items in the list. However, when I set a debug point on the method, the debugger never breaks into that section and none of my code is firing (I've even tried having it write out silly messages just to see if the method is even firing - it's not). Here's the markup:
<asp:CheckBoxList id="chkLanguages" runat="server" AutoPostBack="true" ViewStateMode="Enabled" EnableViewState="true" data-paramname="lcid"
OnSelectedIndexChanged="chkLanguages_SelectedIndexChanged" />
Here's the SelectedIndexChanged event:
protected void chkLanguages_SelectedIndexChanged(object sender, EventArgs e)
{
//Do all the things
}
What am I missing? I feel like it must be something obvious but for the life of me, I can't see it.
Also I should note this is in the latest version of Mono so there might be some weird quirk there that's causing the issue.
One final note, there are no errors in the console if I check the browser developer tools so I don't have any weird javascript stuff going on that's causing an issue.
Update
Since it's been asked, I'm posting the entire page markup and the requisite codebehind.
Markup:
<%# Page Language="C#" MasterPageFile="~/pages/master/main.master" Inherits="Letters.Web.UI.searchLetters" AutoEventWireup="true" %>
<asp:Content runat="server" ContentPlaceHolderID="additionalCSS">
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/letters.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/font-awesome.min.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/bootstrap.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/bootstrap-multiselect.css") %>" />
</asp:Content>
<asp:Content runat="server" ContentPlaceHolderID="additionalJS">
<script type="text/javascript"
src="<%= Page.ResolveClientUrl("~/resources/javascript/bootstrap.min.js") %>">
</script>
<script type="text/javascript"
src="<%= Page.ResolveClientUrl("~/resources/javascript/bootstrap-multiselect.js") %>">
</script>
</asp:Content>
<asp:Content runat="server" ContentPlaceHolderID="mainContent">
<section id="search-header">
<div class="column">
<div class="field-set">
<asp:Label id="lblTextString" runat="server" CssClass="data-label">Search for Letters</asp:Label>
<div class="data-control">
<asp:TextBox id="txtTextString" Width="100%" runat="server" CssClass="form-control searchable" placeholder="Contains Text" data-paramname="textString" />
</div>
</div>
</div>
<div class="column-small">
<div class="field-set">
<span class="data-label"> </span>
<div class="data-control">
<button id="btnSearch" runat="server" class="search-nav-buttons" onserverclick="Search_Click">
Search
</button>
</div>
</div>
</div>
</section>
<asp:PlaceHolder id="plcSearchResults" runat="server">
<section id="search-results">
<div class="filter-options">
<table>
<tbody>
<tr class="searchresults-headerstyle">
<th scope="col" class="header">Filter Options</th>
</tr>
</tbody>
</table>
<asp:Panel id="pnlLanguage" runat="server">
<h1>Languages</h1>
<asp:HiddenField id="hdlLanguages" runat="server" />
<asp:CheckBoxList id="chkLanguages" runat="server" AutoPostBack="true" ViewStateMode="Enabled" EnableViewState="true" data-paramname="lcid"
OnSelectedIndexChanged="chkLanguages_SelectedIndexChanged" />
</asp:Panel>
</div>
<asp:GridView id="grvResults" runat="server" CssClass="table table-striped table-bordered" AutoGenerateColumns="false"
AllowPaging="true" AllowSorting="true" Width="70%" GridLines="None"
OnPageIndexChanging="GridView_PageIndexChanging" >
<HeaderStyle CssClass="searchresults-headerstyle" />
<FooterStyle CssClass="searchresults-footerstyle" />
<PagerStyle CssClass="pagination-style" />
<Columns>
<asp:TemplateField HeaderText="Search Results" >
<ItemTemplate>
<div class="search-result-record">
<asp:HyperLink runat="server" NavigateUrl='<%# Eval("LetterUrl") %>' Text='<%# Letters.Tools.WebUtils.HtmlEncode(Eval("Title").ToString()) %>' />
<span>(<%# Eval("Language") %>)</span>
<span class="keywords">Keywords: <%# Eval("Categories") %></span>
<asp:Label runat="server" CssClss="language" Visible='<%# Eval("LCID").ToString() != "en" %>'>Language: <%# Eval("Language") %></asp:Label>
<div class="search-abstract">
<%# Eval("SearchAbstract") %>
</div>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</section>
</asp:PlaceHolder>
</asp:Content>
Code Behind:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Letters.Domain.Objects;
using Letters.Tools;
namespace Letters.Web.UI
{
public partial class searchLetters : System.Web.UI.Page
{
#region eventhandlers
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack) {
this.BindResults ();
}
}
protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.grvResults.PageIndex = e.NewPageIndex;
this.BindResults ();
}
protected void chkLanguages_SelectedIndexChanged(object sender, EventArgs e)
{
this.hdlLanguages.Value = this.GetSelectedItems (this.chkLanguages);
this.FilterResults ();
}
protected void Search_Click(object sender, EventArgs e)
{
Dictionary<string, object> parameters = new Dictionary<string, object> ();
if (!string.IsNullOrEmpty (this.txtTextString.Text))
parameters.Add (this.txtTextString.Attributes ["data-paramname"].ToString (), this.txtTextString.Text);
this.BindResults (parameters);
}
#endregion
private void FilterResults()
{
Dictionary<string, object> parameters = new Dictionary<string, object> ();
if (pnlLanguage.Visible) {
parameters.Add (this.chkLanguages.Attributes ["data-paramname"].ToString (), this.GetSelectedItems (this.chkLanguages));
}
//Finally, add the search string
if (!string.IsNullOrEmpty (this.txtTextString.Text))
parameters.Add (this.txtTextString.Attributes ["data-paramname"].ToString (), this.txtTextString.Text);
this.BindResults (parameters);
}
private string[] GetFilterOption(string delimitedValue)
{
string[] result = null;
if (delimitedValue.Contains (",")) {
result = delimitedValue.Split (new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
} else
result = new string[] { delimitedValue };
return result;
}
private string GetSelectedItems(CheckBoxList list)
{
StringBuilder result = new StringBuilder ();
foreach (ListItem item in list.Items) {
if (item.Selected)
result.Append (item.Value).Append (",");
}
if (result.Length > 0) {
result.Remove (result.Length - 1, 1);
return result.ToString ();
}
else
return null;
}
private string GetSelectedItems(ListBox list)
{
StringBuilder result = new StringBuilder ();
foreach (ListItem item in list.Items) {
if (item.Selected)
result.Append (item.Value).Append (",");
}
if (result.Length > 0) {
result.Remove (result.Length - 1, 1);
return result.ToString ();
}
else
return null;
}
private void PopulateFilters(List<SearchResult> results)
{
var languages = (from x in results
group x by new { x.LCID, x.Language } into counts
select new { Key = counts.Key.LCID, DisplayName = string.Format("{0} ({1})", counts.Key.Language, counts.Count()) }
).ToList();
this.chkLanguages.DataSource = languages;
this.chkLanguages.DataTextField = "DisplayName";
this.chkLanguages.DataValueField = "Key";
this.chkLanguages.DataBind ();
if (!string.IsNullOrEmpty (hdlLanguages.Value)) {
string[] languageSelect = this.GetFilterOption (hdlLanguages.Value);
foreach (ListItem item in this.chkLanguages.Items) {
if (languageSelect.Contains (item.Value))
item.Selected = true;
}
}
}
private void BindResults()
{
List<SearchResult> results = this.GetSearchResults ();
this.grvResults.DataSource = results;
this.grvResults.DataBind ();
this.PopulateFilters (results);
}
private void BindResults(Dictionary<string, object> parameters)
{
List<SearchResult> results = this.GetSearchResults(parameters);
this.grvResults.DataSource = results;
this.grvResults.DataBind ();
this.PopulateFilters (results);
}
private void RegisterEvents()
{
this.grvResults.PageIndexChanging += new System.Web.UI.WebControls.GridViewPageEventHandler (GridView_PageIndexChanging);
}
private List<SearchResult> GetSearchResults()
{
return LetterService.GetSearchResults ();
}
private List<SearchResult> GetSearchResults(Dictionary<string, object> parameters)
{
return LetterService.GetSearchResults (parameters);
}
}
}

I was never able to find the exact cause to the problem. Every other type of control was able to post back events and I could properly handle their events server-side. I ended up working around this particular issue by ripping out the CheckBoxList and replacing it with a gridview that used an item template to store the value in a hidden field and display the checkbox where I could then handle the OnCheckedChanged event (see code below). This worked brilliantly.
Markup
<asp:GridView id="grvLanguages" runat="server" ShowHeader="false" ShowFooter="false" AllowPaging="false"
AllowSorting="false" GridLines="None" AutoGenerateColumns="false" data-paramname="languages" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField id="hdlValue" runat="server" Value='<%# Eval("Key") %>' />
<asp:CheckBox id="chkDisplay" runat="server" Text='<%# Eval("DisplayName") %>' OnCheckedChanged="chkLanguage_SelectedIndexChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
protected void chkLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
this.hdlLanguages.Value = this.GetSelectedItems (this.grvLanguages);
this.FilterResults ();
}
I'm guessing the problem is probably some weird, esoteric bug in the Mono framework. Like I said, I don't have a problem with ANY other controls (I tested quite a few - all of their server side events handled just fine); it was just a problem with the CheckBoxList.

Related

event handling is not working in my asp.net web forms web application

The update button Onclick event is not working.
I inserted one more button called button1 for testing if it works, but found that it is not working, even Icacked in other web forms in the app
It is not working at all.
Only page load event-driven is working.
Update:
The problem is not solved with other controls. For example, after the user clicks on an update button, a fucntion will be called that checks the value in the textbox and make some calculation.
After debugging, I found that the program cannot read any values from the textbox.
Note: I am using packages like bootstrap, Ajax as they are already built-in in the asp.net web forms web applications. I have also tried to exclude them from the project as mentioned in some references, however, nothing changed.
Here is my code for Shopping Cart web form:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Celebreno.Models;
using Celebreno.Cart;
//to use IOrderedDictionary
using System.Collections.Specialized;
using System.Collections;
using System.Web.ModelBinding;
namespace Celebreno
{
public partial class ShowCart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//2- Display the total of cart by calling GetTotal() function(located in Actions_of_Cart class)
//and then store the return value in a new variable, then dispaly it in a label
using (Actions_of_Cart usersShoppingCart = new Actions_of_Cart())
{
//declare a new variable to store the total into it
decimal cartTotal = 0;
cartTotal = usersShoppingCart.GetTotal();
if (cartTotal > 0)
{
//Display Total in a label that has property " Enable ViewState = False"
// ViewSate used
LblTotal.Text = String.Format("{0:c}", cartTotal);
}
else
{
LblTotalText.Text = "";
LblTotal.Text = "";
//HtmlGenericControl
ShoppingCartTitle.InnerText = "The Shopping Cart is Empty";
//not yet needed
UpdateBtn.Visible = false;
// CheckoutImageBtn.Visible = false;
}
Button1.Click += Button1_Click;
}
}
//1- decalre the "select Method" (used in GridView in Source Code) to return the value of..
//..calling GetCartItems(), which is defined in Actions_of_Cart DB class
public List<ItemsInCart> GetShoppingCartItems()
{
Actions_of_Cart actions = new Actions_of_Cart();
return actions.GetCartItems();
}
//
public List<ItemsInCart> UpdateCartItems()
{
using (Actions_of_Cart usersShoppingCart = new Actions_of_Cart())
{
//new var
String cartId = usersShoppingCart.GetCartId();
//The UpdateCartItems method gets the updated values for each item in the shopping cart.
//Then, the UpdateCartItems method calls the UpdateShoppingCartDatabase method
//to either add or remove items from the shopping cart.
//Once the database has been updated to reflect the updates to the shopping cart,
//the GridView control is updated on the shopping cart page by calling the DataBind method
//for the GridView. Also, the total order amount on the shopping cart page is updated
//to reflect the updated list of items.
Actions_of_Cart.ShoppingCartUpdates[] cartUpdates = new Actions_of_Cart.ShoppingCartUpdates[CartList.Rows.Count];
for (int i = 0; i < CartList.Rows.Count; i++)
{
IOrderedDictionary rowValues = new OrderedDictionary();
rowValues = GetValues(CartList.Rows[i]);
//ProductId related to struct in Actions
cartUpdates[i].ProductId = Convert.ToInt32(rowValues["ID"]);
CheckBox cbRemove = new CheckBox();
cbRemove = (CheckBox)CartList.Rows[i].FindControl("RemoveItem");
cartUpdates[i].RemoveItem = cbRemove.Checked;
TextBox quantityTextBox = new TextBox();
quantityTextBox = (TextBox)CartList.Rows[i].FindControl("PurchaseQuantity");
cartUpdates[i].PurchaseQuantity = Convert.ToInt16(quantityTextBox.Text.ToString());
}
usersShoppingCart.UpdateShoppingCartDatabase(cartId, cartUpdates);
CartList.DataBind();
//dispaly updated total value
LblTotal.Text = String.Format("{0:c}", usersShoppingCart.GetTotal());
return usersShoppingCart.GetCartItems();
}
}
public static IOrderedDictionary GetValues(GridViewRow row)
{
try
{
IOrderedDictionary values = new OrderedDictionary();
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.Visible)
{
// Extract values from the cell.
cell.ContainingField.ExtractValuesFromCell(values, cell, row.RowState, true);
}
}
return values;
}
catch (Exception exp)
{
throw new Exception("ERROR1" + exp.Message.ToString(), exp);
}
}
protected void UpdateBtn_Click(object sender, EventArgs e)
{
UpdateCartItems();
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "IT is working ";
}
}
}
Source Code:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ShowCart.aspx.cs" Inherits="Celebreno.ShowCart" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<div id="ShoppingCartTitle" runat="server" class="ContentHead"><h1>Shopping Cart</h1></div>
<%--Start of the GridView to display the items in the cart--%>
<asp:GridView ID="CartList" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="Vertical" CellPadding="4"
ItemType="Celebreno.Models.ItemsInCart" SelectMethod="GetShoppingCartItems"
CssClass="table table-striped table-bordered" >
<Columns>
<%--problem solved : change "ID" to "ServicePack.ID"--%>
<asp:BoundField DataField="ServicePack.ID" HeaderText="Service Package ID" SortExpression="ID" />
<asp:BoundField DataField="ServicePack.Provider" HeaderText="Provider" />
<asp:BoundField DataField="ServicePack.UnitPrice" HeaderText="Price (each)" DataFormatString="{0:c}"/>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="PurchaseQuantity" Width="40" runat="server" Text="<%#: Item.Quantity %>"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Total">
<ItemTemplate>
<%#: String.Format("{0:c}", ((Convert.ToDouble(Item.Quantity)) * Convert.ToDouble(Item.ServicePack.UnitPrice)))%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remove Item">
<ItemTemplate>
<%--checkbox for removing the item--%>
<asp:CheckBox id="Remove" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%--End of the GridView--%>
<div>
<p></p>
<strong>
<%--2 (display the total of the cart--%>
<asp:Label ID="LblTotalText" runat="server" Text="Order Total: "></asp:Label>
<asp:Label ID="LblTotal" runat="server" EnableViewState="false"></asp:Label>
</strong>
</div>
<br />
<table>
<tr>
<td>
<%--3 ( add update button) --%>
</td>
<td>
<asp:Button ID="UpdateBtn" runat="server" Text="Button" OnClick="UpdateBtn_Click" />
<asp:Button ID="Button1" runat="server" Text="Test" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Test"></asp:Label>
</td>
</tr>
</table>
</asp:Content>
solved : by adding two attributes as shown below
<asp:Button ID="UpdateBtn" runat="server" OnClick="UpdateBtn_Click" Text="Button" CausesValidation="False" UseSubmitBehavior="false" />

Print ArrayList data to ASP.NET page using GridView

Trying to print the stored data of arraylist to the gridview.
.aspx File, Working perfectly fine.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Stock Management System</title>
<style>
body{
background-color:#63AA9C;
text-align:center
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center" border="0" style="background-color:lightcoral">
<tr><td>Item Name:</td><td><asp:TextBox ID="Name" placeholder="Item Name" runat="server"></asp:TextBox></td></tr>
<tr><td>Quantity:</td><td><asp:TextBox ID="Quan" placeholder="Quantity" runat="server"></asp:TextBox></td></tr>
<tr><td>Price:</td><td><asp:TextBox ID="Pri" placeholder="Price" runat="server"></asp:TextBox></td></tr>
<tr><td>Description:</td><td><asp:TextBox ID="Desc" placeholder="Descrition" runat="server"></asp:TextBox></td></tr>
<tr><td><asp:Button ID="Save" runat="server" Text="Store Data" OnClientClick="Store()" width="200px"/></td></tr>
<tr><td><asp:Button ID="Show" runat="server" Text="Show Data" OnClientClick="Print()" width="200px" /></td></tr>
<tr><td><asp:Button ID="Delete" runat="server" Text="Remove Last Added Data" OnClientClick="Remove()" width="200px" /></td></tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="LightCoral" ></asp:GridView>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="true" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="LightCoral" ></asp:GridView>
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="true" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="LightCoral"></asp:GridView>
<asp:GridView ID="GridView4" runat="server" AutoGenerateColumns="true" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="LightCoral"></asp:GridView>
</div>
</form>
</body>
</html>
.aspx.cs File
No error, but not working while pressing the show data button.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
namespace WebApplication4
{
public partial class WebForm1 : System.Web.UI.Page
{
ArrayList items = new ArrayList();
ArrayList price = new ArrayList();
ArrayList quantity = new ArrayList();
ArrayList description = new ArrayList();
static int a = 0;
protected GridView GridView1;
protected GridView GridView2;
protected GridView GridView3;
protected GridView GridView4;
protected void Page_Load(object sender, EventArgs e)
{
}
public void Store()
{
items.Add(Name.Text);
price.Add(Pri.Text);
quantity.Add(Quan.Text);
description.Add(Desc.Text);
a++;
}
public void Print()
{
GridView1.DataSource = items;
GridView1.DataBind();
GridView2.DataSource = quantity;
GridView2.DataBind();
GridView3.DataSource = price;
GridView3.DataBind();
GridView4.DataSource = description;
GridView4.DataBind();
}
public void Remove()
{
if (a > 0)
{
items.RemoveAt(a);
a--;
}
}
}
}
My page, Trying to show stored data
About the attribute OnClientClick you are using, The documentation says
Gets or sets the client-side script that executes when a Button control's Click event is raised.
which means you are trying to execute a JavaScript function called "Print" in your code (same goes with other buttons).
You should check Button.Click event instead.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.click(v=vs.110).aspx

Retrieve Selected Checkbox Value From Previous Page

I have an asp.net webform website which stores data in a session and on the 3rd page displays the entries entered on pg1 & pg2.
On the first page the first checkboxes is pre-selected by default but if the user selects/unselects a checkbox, when the user is on the second page, there is a back button but when it's clicked I don't know how to re-show the checkboxes selected/unselected as only the default one is checked.
I'm new to using ASP and session storing so I may be doing something completely wrong. How can I resolve my situation?
My code is:
HTML
<div class="form-group">
<div class="col-xs-offset-0 col-sm-offset-4 col-sm-3">All services</div>
<div class="col-sm-1">
<asp:CheckBox ID="Step02AllServices" runat="server" Checked="True" />
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-0 col-sm-offset-4 col-sm-3">Site content uploading only</div>
<div class="col-sm-1">
<asp:CheckBox ID="Step02ContentUploading" runat="server" />
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-0 col-sm-offset-4 col-sm-3">Site content & layout checking</div>
<div class="col-sm-1">
<asp:CheckBox ID="Step02ContentLayoutChecking" runat="server" Enabled="False" />
</div>
</div>
Code Behind
protected void Step02SubmitButton_Click(object sender, EventArgs e)
{
Session["Step02AllServices"] = Step02AllServices.Checked;
Session["Step02ContentUploading"] = Step02ContentUploading.Checked;
Session["Step02ContentLayoutChecking"] = Step02ContentLayoutChecking.Checked;
Response.Redirect("/Quotation/pg3.aspx");
}
I know that is needs to be in my Page_Load just not sure how to do it.
The below is what I have for radio buttons and test fields on another page
if (txtData2.Text == string.Empty && Session["pg2"] != null)
{
txtData2.Text = Session["pg2"].ToString();
if (Session["pg2Yes"].ToString() == "Yes")
{
pg2Yes.Checked = Session["pg2Yes"].Equals("Yes");
}
if (Session["pg2No"].ToString() == "No")
{
pg2No.Checked = Session["pg2No"].Equals("No");
}
}
Let's assume that you are on page 3 and you clicked the back button which redirects you to page 2.
On load of page 2, you need to check whether it's a new load (not postback) and if it contains the values on session. If both are true, you need to get the value from session and make the checkbox selected.
So, write the following code in Page2Load
//if you are loading the new page
if (!Page.IsPostBack)
{
if(Session["Step02AllServices"] != null)
{
Step02AllServices.Checked = (bool) Session["Step02AllServices"];
//similarly assign other checkbox values as they are in session already
}
else
{
//do normal assignment
}
}
check the below simple implementation and enhance it according to your requirement and can be done using single page
aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="div1" runat="server">
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CheckBox ID="CheckBox2" runat="server" /><asp:Button ID="Button1" runat="server" Text="Next" OnClick="Button1_Click" />
</div>
<div id="div2" runat="server" visible="false">
<asp:Button ID="Button2" runat="server" Text="Back" OnClick="Button2_Click"/>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button3" runat="server" Text="Next" OnClick="Button3_Click"/>
</div>
<div id="div3" runat="server" visible="false">
<asp:Button ID="Button4" runat="server" Text="Back" OnClick="Button4_Click"/>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label4" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
cs code:
using System;
namespace WebApplication1
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
div1.Visible = false;
div2.Visible = true;
div3.Visible = false;
}
protected void Button2_Click(object sender, EventArgs e)
{
div1.Visible = true;
div2.Visible = false;
div3.Visible = false;
}
protected void Button3_Click(object sender, EventArgs e)
{
div1.Visible = false;
div2.Visible = false;
div3.Visible = true;
Label1.Text = CheckBox1.Checked.ToString();
Label2.Text = CheckBox2.Checked.ToString();
Label3.Text = TextBox1.Text;
Label4.Text = TextBox2.Text;
}
protected void Button4_Click(object sender, EventArgs e)
{
div1.Visible = false;
div2.Visible = true;
div3.Visible = false;
}
}
}

updatepanel and javascript include file

I have found many solution for my issue but none doesn't work in my scenario.
I have created a test project to demo my concept.
Basically, there is a page that host a user control...
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
WebUserControl1 has a dropdownlist and two other webusercontrols (to be displayed based on the selection of dropdownlist element) inside updatepanel as below.
<%# Register Src="WebUserControl2.ascx" TagName="WebUserControl2" TagPrefix="uc2" %>
<%# Register Src="WebUserControl3.ascx" TagName="WebUserControl3" TagPrefix="uc3" %>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
</asp:DropDownList>
<asp:Panel ID="pnlCreditCard" Visible="false" runat="server">
<uc2:WebUserControl2 ID="WebUserControl21" runat="server" />
</asp:Panel>
<asp:Panel ID="pnlGiftCard" Visible="false" runat="server">
<uc3:WebUserControl3 ID="WebUserControl31" runat="server" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Code behind file for WebUserControl1 is .....
public enum PaymentMethod
{
CreditCard = 0,
GiftCard
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindPaymentMethods(Enum.GetValues(typeof(PaymentMethod)));
}
private void BindPaymentMethods(Array paymentMethods)
{
DropDownList1.DataSource = paymentMethods;
DropDownList1.DataBind();
if (paymentMethods.Length > 0)
{
DropDownList1.SelectedIndex = 0;
UpdateCreditOrGiftCardPanelVisibility();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateCreditOrGiftCardPanelVisibility();
}
private void UpdateCreditOrGiftCardPanelVisibility()
{
if(DropDownList1.SelectedValue == Enum.GetName(typeof(PaymentMethod),PaymentMethod.CreditCard))
{
pnlGiftCard.Visible = false;
pnlCreditCard.Visible = true;
}
else if (DropDownList1.SelectedValue == Enum.GetName(typeof(PaymentMethod), PaymentMethod.GiftCard))
{
pnlCreditCard.Visible = false;
pnlGiftCard.Visible = true;
}
}
Now, the problem starts here...There is an external javascript file [JScript1.js] (embedded resource) which basically is used to display an alert box.
<script language="javascript" type="text/javascript">
window.onload = function() {
alert('creditcard form');
}
WebUserControl2.ascx.cs code behind is
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptInclude(this.Page, this.Page.GetType().BaseType, "JScript1", Page.ClientScript.GetWebResourceUrl(this.Page.GetType().BaseType, "WebApplication1.JScript1.js"));
}
Alert window doesn't get displayed when I change the dropdownlist value. Even the script is getting registered three times (look in the firebug)
Need to use ScriptInclude instead of ScriptBlock as the original JS file is too big.
Can email the test app....
Thanks in Advance
After working around a bit, I found the solution.
I registered a ScriptManagerProxy in WebUserControl2.ascx
<asp:ScriptManagerProxy ID="ScriptManager1" runat="server" >
<Scripts>
<asp:ScriptReference Assembly="WebApplication1" Name="WebApplication1.JScript1.js" />
</Scripts>
</asp:ScriptManagerProxy>
Then on the code behind of the same control, added...
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ScriptManager.RegisterStartupScript(this, GetType(), "test", "doSomething();", true);
}
and the JScript1.js file looks like below.
function doSomething() {
alert('via dosomething control2 form');
}
Hope that helps. Though I had to litter around more in my practical scenario but this was certainly the way I got it working.
Thanks,

advancing to button code-behind when validation fails... how to solve it without Page.IsValid?

I have an ASP .NET page with both asp .net validators and some javascript checking too.
I am advancing into the button code behind:
protected void Button2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
/// ...
Even when the validation fails!
The Page.IsValid check solves it, but it also resets all the JavaScript variables… May there be a way not to advance into the button code?
I have an ajax update panel and some image buttons on the page too… Anything I may look out for?
Thanks in advance!
Here is my aspx:
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="WebForm2.aspx.cs"
Inherits="WebForm2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div style="width: 500px;">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script type="text/javascript">
var nrOptions = 0;
alert(nrOptions + " - variable initialized");
function IncrementQuantity() {
nrOptions++;
alert(nrOptions);
}
function DecrementQuantity() {
nrOptions--;
alert(nrOptions);
}
function MoreThanTwo() {
alert(nrOptions);
if (nrOptions > 1) {
alert('okay - you have: ' + nrOptions);
return true;
}
else {
alert('error - must have at least two options, you only have: ' + nrOptions);
return false;
}
}
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
Fill in with two or more options:<br />
<table border="1" width="100%">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td valign="middle">
</td>
<td valign="middle">
Description:
<asp:TextBox ID="TBox1" runat="server" Width="120px" Text='<%# Eval("Desc")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TBox1"
ValidationGroup="InsertVal" ErrorMessage="*"></asp:RequiredFieldValidator>
Points:
<asp:TextBox ID="TBox2" runat="server" Width="20px" Text='<%# Eval("Pont")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TBox2"
ValidationGroup="InsertVal" ErrorMessage="*"></asp:RequiredFieldValidator>
<asp:Button ID="ImageButton1" runat="server" Text="x" CommandName="DeleteRow" OnClientClick="DecrementQuantity();" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TBox2"
ValidationExpression="\d+" ValidationGroup="InsertVal" runat="server"
ErrorMessage="Number >= 0."></asp:RegularExpressionValidator>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
<tr>
<td colspan="2" align="right">
<asp:Button ID="lnkAddRow" runat="server" Text="Add option" OnClientClick="IncrementQuantity();"
CommandName="AddRow" OnClick="lnkAddRow_Click" />
</td>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
<br />
<p style="text-align: right;">
<asp:Button ID="Button2" runat="server" Text="Save" OnClick="Button2_Click" OnClientClick="return MoreThanTwo();"
ValidationGroup="InsertVal" />
</p>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
And my code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DTable = EmptyDTOptions();
Repeater1.DataSource = DTable;
Repeater1.DataBind();
}
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "AddRow")
{
DTable.Rows.Add(0, "", "");
Repeater1.DataSource = DTable;
Repeater1.DataBind();
return;
}
if (e.CommandName == "DeleteRow")
{
int idx = e.Item.ItemIndex;
DTable.Rows.RemoveAt(idx);
Repeater1.DataSource = DTable;
Repeater1.DataBind();
return;
}
}
protected void lnkAddRow_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
int idx = item.ItemIndex;
TextBox tb1 = (TextBox)item.FindControl("TBox1");
TextBox tb2 = (TextBox)item.FindControl("TBox2");
DTable.Rows[idx]["Desc"] = tb1.Text;
DTable.Rows[idx]["Pont"] = tb2.Text;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
// save!
}
}
private DataTable DTable
{
get
{
DataTable _dt = (DataTable)Session["DTable"];
if (Object.Equals(_dt, null))
{
_dt = EmptyDTOptions();
Session.Add("DTable", _dt);
}
return _dt;
}
set
{
Session["DTable"] = value;
}
}
DataTable EmptyDTOptions()
{
DataTable dt = new DataTable();
DataColumn dc;
dc = new DataColumn("OptionNr", System.Type.GetType("System.Int32"));
dt.Columns.Add(dc);
dc = new DataColumn("Desc");
dt.Columns.Add(dc);
dc = new DataColumn("Pont");
dt.Columns.Add(dc);
return dt;
}
}
I think it shows what I'm trying to avoid... Advancing to the button2_click with the failed validation (and resetting the javascript variable)... In order to get a list of two or more pairs of items, one of them being a number.
Rather than calling your function from the OnClientClick on the button, you can add a CustomValidator that calls your JavaScript function.
<asp:CustomValidator ID="CheckMoreThanTwo" runat="server"
ValidationGroup="InsertVal"
ClientValidationFunction="MoreThanTwo" />
Then, modify your JavaScript function as follows:
function MoreThanTwo(source, arguments) {
alert(nrOptions);
if (nrOptions > 1) {
alert('okay - you have: ' + nrOptions);
arguments.IsValid=true;
} else {
alert('error - must have at least two options, you only have: '
+ nrOptions);
arguments.IsValid=false;
}
}
Doing this allows your custom JavaScript validation to work with all the validation code that ASP.NET uses. For instance, if you change to a validation summary, or change validation groups, this custom validator will continue to work the way the rest of the validators work.

Categories