Change of input creates an error - c#

Default.aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Greeting Card Maker</title>
</head>
<body>
<form runat="server">
<div>
<!-- Here are the controls -->
Choose a background color: <br />
<asp:DropDownList ID="backColor" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ControlChanged" Width="194px" Height="22px" /> <br /><br />
Choose a font:<br />
<asp:DropDownList ID="fontName" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ControlChanged" Width="194px" Height="22px" /><br /><br />
Specify a numeric font size:<br />
<asp:TextBox ID="txtFontSize" AutoPostBack="true" runat="server" OnTextChanged="ControlChanged"/><br /><br />
Choose a border style:<br />
<asp:RadioButtonList ID="border" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ControlChanged" Width="177px" Height="59px" /><br /><br />
<asp:CheckBox ID="chkPicture" AutoPostBack ="true" runat="server" OnCheckedChanged="ControlChanged" Text="Add the Default Picture"></asp:CheckBox><br /><br />
Enter the greeting text below:<br />
<asp:TextBox ID="txtGreeting" AutoPostBack="true" runat="server" OnTextChanged="ControlChanged" Width="240px" Height="85px" TextMode="MultiLine" /><br /><br />
<asp:Button ID="cmdUpdate" OnClick="cmdUpdate_Click" runat="server" Width="71px" Height="24px" Text="Update" />
</div>
<!-- Here is the card -->
<asp:Panel ID="pnlCard" runat="server" Width="339px" Height="481px" HorizontalAlign="Center" Style="position: absolute;
top: 16px; left:313px;">
<br />
<asp:Label ID="lblGreeting" runat="server" Width="212px" Height="160px" />
<asp:Image ID="imgDefault" runat="server" Width="212px" Height="160px" />
</asp:Panel>
</form>
</body>
</html>
The page is supposed to dynamically change when the options of the inputs are changed. When the page first loads and I go to select one of the options in the background color I get the error on this line of code.
//Update the border style using the value from the converter
pnlCard.BorderStyle = (BorderStyle)converter.ConvertFromString(border.SelectedItem.Text);
The error is object reference not set to an instance of an object. I have tried deciphering the other similar questions and have not figured it out.
here is the rest of my Default.aspx.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Text;
using System.ComponentModel;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack)
{
//Set color options
string[] colorArray = Enum.GetNames(typeof(System.Drawing.KnownColor));
backColor.DataSource = colorArray;
backColor.DataBind();
//Set font options
InstalledFontCollection fonts = new InstalledFontCollection();
foreach (System.Drawing.FontFamily family in fonts.Families)
{
fontName.Items.Add(family.Name);
}
//Set border style options
string[] borderStyleArray = Enum.GetNames(typeof(BorderStyle));
border.DataSource = borderStyleArray;
border.DataBind();
imgDefault.ImageUrl = "defaultPic.png";
imgDefault.Visible = false;
}
}
protected void ControlChanged(object Sender, System.EventArgs e)
{
UpdateCard();
}
protected void cmdUpdate_Click(object sender, EventArgs e)
{
UpdateCard();
}
private void UpdateCard()
{
//Find the appropriate TypeConverter for the BorderSyle enumeration
TypeConverter converter = TypeDescriptor.GetConverter(typeof(BorderStyle));
//Update the border style using the value from the converter
pnlCard.BorderStyle = (BorderStyle)converter.ConvertFromString(border.SelectedItem.Text);
//Update the font
lblGreeting.Font.Name = fontName.SelectedItem.Text;
if(Int32.Parse(txtFontSize.Text) > 0)
{
lblGreeting.Font.Size = FontUnit.Point(Int32.Parse(txtFontSize.Text));
}
if(chkPicture.Checked)
{
imgDefault.Visible = true;
}
else
{
imgDefault.Visible = false;
}
lblGreeting.Text = txtGreeting.Text;
}
}
Here is the stack trace
[NullReferenceException: Object reference not set to an instance of an object.]
_Default.UpdateCard() in c:\Users\WES\Documents\Semester 6\DistributedAppDevelopment\Module3AssignmentWesMincic\Default.aspx.cs:61
_Default.ControlChanged(Object Sender, EventArgs e) in c:\Users\WES\Documents\Semester 6\DistributedAppDevelopment\Module3AssignmentWesMincic\Default.aspx.cs:47
System.Web.UI.WebControls.ListControl.OnSelectedIndexChanged(EventArgs e) +116
System.Web.UI.WebControls.DropDownList.RaisePostDataChangedEvent() +138
System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent() +15
System.Web.UI.Page.RaiseChangedEvents() +132
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1559

Related

SelectedIndexChange Not Firing Correctly

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.

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;
}
}
}

how to perform addition using a textbox [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a Text box. On button click event the value of Text box should be displayed in a label as result.
On clicking the button again and giving some input in the Text box the input should get added to the result.
I mean repeating the button clicks and providing input should get added o the result.
How to perform this?
I am still getting error
"System.FormatException: Input string was not in a correct format."
Error is regarding: lblconsumed.Text = (int.Parse(lblconsumed.Text) + userValue).ToString();
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplication1.ServRef;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
ServRef.ProteinServiceClient sc = new ServRef.ProteinServiceClient();
UserDetail userinfo = new UserDetail();
protected void Page_Load(object sender, EventArgs e)
{
// ddlUser.DataSource = sc.AddUser(userinfo);
BindUserDetails();
}
protected void BindUserDetails()
{
IList<UserDetail> objUserDetails = new List<UserDetail>();
//objUserDetails = objService.GetUserDetails("");
objUserDetails = sc.GetAllUser("");
ddlUser.DataSource = objUserDetails;
ddlUser.DataBind();
}
protected void btnAddUser_Click(object sender, EventArgs e)
{
userinfo.user_name = tbname.Text.Trim();
userinfo.user_goal = Convert.ToInt32(tbgoal.Text.Trim());
string result = sc.AddUser(userinfo);
lblgoal.Text = Convert.ToString(userinfo.user_goal);
}
protected void Button2_Click(object sender, EventArgs e)
{
int userValue;
if (int.TryParse(tbamount.Text, out userValue))
{
lblconsumed.Text = (int.Parse(lblconsumed.Text) + userValue).ToString();
}
}
}
}`
My aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="Style.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div id="main">
<h2>Protein Tracker</h2>
<div id="selectuser">
<label for="select-users">Select a user&nbsp: </label>
<asp:DropDownList ID="ddlUser" runat="server"
Width="60px" AutoPostBack="True"
DataTextField="user_name"
DataValueField="user_name" ></asp:DropDownList>
</div>
<hr />
<div id="adduser">
<h2>Add new user</h2>
<label for="name">User Name&nbsp:</label>
<asp:TextBox ID="tbname" runat="server" style="margin-left: 10px"></asp:TextBox>
<br /><br />
<label for="goal">User Goal&nbsp:</label>
<asp:TextBox ID="tbgoal" runat="server" style="margin-left: 20px"></asp:TextBox>
<br /><br />
<asp:Button ID="btnAddUser" runat="server" Text="Add" style="margin-left: 210px" OnClick="btnAddUser_Click" />
</div>
<hr />
<div id="addprotein">
<h2>Add protein</h2>
<label for="amount">Amount&nbsp:</label>
<asp:TextBox ID="tbamount" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button2" runat="server" Text="Add" style="margin-left: 180px" OnClick="Button2_Click"/>
</div>
<hr />
<div>
<p>Total Consumed&nbsp:&nbsp <asp:Label ID="lblconsumed" runat="server" Text=""></asp:Label></p>
<p>Goal Set&nbsp:&nbsp <asp:Label ID="lblgoal" runat="server" Text=""></asp:Label></p>
</div>
</div>
</form>
</body>
</html>
#user3174595 : I have put in the simple code. its the easiest operation that can be performed.
form1.aspx
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br />
<asp:Label ID="Label1" runat="server" Text="0" ></asp:Label>
</div>
</form>
form1.aspx.cs
public partial class addition : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
double userValue = 0;
if (double.TryParse(TextBox1.Text,out userValue))
{
Label1.Text = (double.Parse(Label1.Text) + userValue).ToString();
}
}
}

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.

The footer CSS does not work when the page loads dynamic content at button click

.html
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>
<link href="dark.css" rel="stylesheet" type="text/css" id="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:Label ID="CaptionLabel" runat="server"></asp:Label>
<asp:TextBox ID="NumberTextbox" runat="server">(empty)</asp:TextBox>
<asp:Button ID="SquareButton" runat="server" Text="Square" style="background-color:Blue; color:White;" />
<asp:Label ID="ResultLabel" runat="server" Text="(empty)" CssClass="reverse"></asp:Label>
<p>
<asp:Label ID="Label1" runat="server" CssClass="footer1"
Text="Label Label Label Label LabelLabelLabel Label Label Label Label Label Label Label"></asp:Label>
</p>
<asp:RadioButton ID="radioDark" runat="server" AutoPostBack="True"
Checked="True" GroupName="grpSelectStylesheet"
oncheckedchanged="SwitchStylesheets" Text="Dark" />
<br />
<asp:RadioButton ID="radioLight" runat="server" AutoPostBack="True"
GroupName="grpSelectStylesheet" oncheckedchanged="SwitchStylesheets"
Text="Light" />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SwitchStylesheets(object sender, EventArgs e)
{
if (radioDark.Checked)
stylesheet.Href = "dark.css";
if (radioLight.Checked)
stylesheet.Href = "light.css";
}
protected void Button1_Click(object sender, EventArgs e)
{
int count=DateTime.Now.Second;
for (int i = 0; i < count; i++)
{//for
Label q = new Label();
q.ID = DateTime.Now.Second.ToString();
q.Text = DateTime.Now.Second.ToString();
string spacee = "<br />";
Label space = new Label();
space.Text = spacee;
form1.Controls.Add(q);
form1.Controls.Add(space);
}//for
}
}
When the button is clicked, it works as it should but the footer does not register the expansion of the page.
Your code is completely wrong. you cannot change the stylesheet like this for a control even if the autopostback is set to true.
UPDATE: Here's how you should do it:
1- Remove the .css reference from your page.
2- Add this method to your page:
private void UpdateStylesheet(string filepath)
{
HtmlLink newStyleSheet = new HtmlLink();
newStyleSheet.Href = filepath;
newStyleSheet.Attributes.Add("type", "text/css");
newStyleSheet.Attributes.Add("rel", "stylesheet");
Page.Header.Controls.Add(newStyleSheet);
}
3- Add this line to your page_load event:
UpdateStylesheet("dark.css");
4- Handle the SwitchStylesheets like this:
if (radioDark.Checked)
UpdateStylesheet("dark.css");
if (radioLight.Checked)
UpdateStylesheet("light.css");

Categories