This post is gives you some solutions for 9 real life application problems in asp.net:
- How to display number as words?
- How to compute data (sum, count, …) in a data table?
- How to display client date time?
- How to call javascript from server side(code behind)?
- What is the Difference between <% … %>, <%= … %>, <%# … %>, <%@ … %>, <%$ … %>?
- How to maintain scroll bar on postback?
- How to use the enter key to submit a form?
- How to call page methods from client side using ajax.net?
- How to capitalize each word in a string?
You can download all samples
Question 1: How to display number as words?
In certain applications such as in financial applications or payment operations, it is interesting to convert numbers as words. This piece of code allows you to display numbers in words:
- public static class MyConvert
- {
-
- private static readonly string[] _smallNumbers = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
- "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen",
- "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
-
-
- private static readonly string[] _tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty",
- "Ninety"};
-
-
- private static readonly string[] _scaleNumbers = { "", "Thousand", "Million", "Billion" };
-
- public static string NumberToWords(int number)
- {
-
- if (number == 0)
- return _smallNumbers[0];
-
-
- int[] digitGroups = new int[4];
-
-
- int positive = Math.Abs(number);
-
-
- for (int i = 0; i < 4; i++)
- {
- digitGroups[i] = positive % 1000;
- positive /= 1000;
- }
-
-
- string[] groupText = new string[4];
-
- for (int i = 0; i < 4; i++)
- groupText[i] = ThreeDigitGroupToWords(digitGroups[i]);
-
-
-
- string combined = groupText[0];
- bool appendAnd;
-
-
- appendAnd = (digitGroups[0] > 0) && (digitGroups[0] < 100);
-
-
- for (int i = 1; i < 4; i++)
- {
-
- if (digitGroups[i] != 0)
- {
-
- string prefix = groupText[i] + " " + _scaleNumbers[i];
-
- if (combined.Length != 0)
- prefix += appendAnd ? " and " : ", ";
-
-
- appendAnd = false;
-
-
- combined = prefix + combined;
- }
- }
-
-
- if (number < 0)
- combined = "Negative " + combined;
-
- return combined;
-
- }
-
-
- private static string ThreeDigitGroupToWords(int threeDigits)
- {
-
- string groupText = "";
-
-
- int hundreds = threeDigits / 100;
- int tensUnits = threeDigits % 100;
-
-
- if (hundreds != 0)
- {
- groupText += _smallNumbers[hundreds] + " Hundred";
-
- if (tensUnits != 0)
- groupText += " and ";
- }
-
-
-
- int tens = tensUnits / 10;
- int units = tensUnits % 10;
-
-
- if (tens >= 2)
- {
- groupText += _tens[tens];
- if (units != 0)
- groupText += " " + _smallNumbers[units];
- }
- else if (tensUnits != 0)
- groupText += _smallNumbers[tensUnits];
-
- return groupText;
- }
- }
public static class MyConvert
{
// Single-digit and small number names
private static readonly string[] _smallNumbers = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen",
"Sixteen", "Seventeen", "Eighteen", "Nineteen"};
// Tens number names from twenty upwards
private static readonly string[] _tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty",
"Ninety"};
// Scale number names for use during recombination
private static readonly string[] _scaleNumbers = { "", "Thousand", "Million", "Billion" };
public static string NumberToWords(int number)
{
// Zero rule
if (number == 0)
return _smallNumbers[0];
// Array to hold four three-digit groups
int[] digitGroups = new int[4];
// Ensure a positive number to extract from
int positive = Math.Abs(number);
// Extract the three-digit groups
for (int i = 0; i < 4; i++)
{
digitGroups[i] = positive % 1000;
positive /= 1000;
}
// Convert each three-digit group to words
string[] groupText = new string[4];
for (int i = 0; i < 4; i++)
groupText[i] = ThreeDigitGroupToWords(digitGroups[i]);
// Recombine the three-digit groups
string combined = groupText[0];
bool appendAnd;
// Determine whether an 'and' is needed
appendAnd = (digitGroups[0] > 0) && (digitGroups[0] < 100);
// Process the remaining groups in turn, smallest to largest
for (int i = 1; i < 4; i++)
{
// Only add non-zero items
if (digitGroups[i] != 0)
{
// Build the string to add as a prefix
string prefix = groupText[i] + " " + _scaleNumbers[i];
if (combined.Length != 0)
prefix += appendAnd ? " and " : ", ";
// Opportunity to add 'and' is ended
appendAnd = false;
// Add the three-digit group to the combined string
combined = prefix + combined;
}
}
// Negative rule
if (number < 0)
combined = "Negative " + combined;
return combined;
}
// Converts a three-digit group into English words
private static string ThreeDigitGroupToWords(int threeDigits)
{
// Initialise the return text
string groupText = "";
// Determine the hundreds and the remainder
int hundreds = threeDigits / 100;
int tensUnits = threeDigits % 100;
// Hundreds rules
if (hundreds != 0)
{
groupText += _smallNumbers[hundreds] + " Hundred";
if (tensUnits != 0)
groupText += " and ";
}
// Determine the tens and units
int tens = tensUnits / 10;
int units = tensUnits % 10;
// Tens rules
if (tens >= 2)
{
groupText += _tens[tens];
if (units != 0)
groupText += " " + _smallNumbers[units];
}
else if (tensUnits != 0)
groupText += _smallNumbers[tensUnits];
return groupText;
}
}
To get the full source code click here.
Question 2: How to compute data (sum, count …) in a data table?
Sometimes it may be interesting to do some operations (sum, average ...) directly on a data table. The following example shows you how to display total in the footer of a gridview control.

- <%@ Page Language="C#" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <script runat="server">
-
- public int Total { get; set; }
-
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- System.Data.DataTable dtItems = new System.Data.DataTable();
- dtItems.Columns.Add("ItemName", typeof(string));
- dtItems.Columns.Add("Price", typeof(int));
-
- dtItems.Rows.Add("Bike", 350);
- dtItems.Rows.Add("Cell Phones", 200);
- dtItems.Rows.Add("Book", 35);
-
- Total = Convert.ToInt32(dtItems.Compute("Sum(Price)", null));
-
- //Binding gridview
- grvItems.DataSource = dtItems;
- grvItems.DataBind();
- }
- }
- </script>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:GridView ID="grvItems" runat="server" ShowFooter="True"
- AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333"
- GridLines="None">
- <RowStyle BackColor="#EFF3FB" />
- <Columns>
- <asp:BoundField FooterText="Total" DataField="ItemName" HeaderText="Item" />
- <asp:TemplateField HeaderText="Price">
- <ItemTemplate>
- <%# Eval("Price")%>
- </ItemTemplate>
- <FooterTemplate>
- <%= Total %>
- </FooterTemplate>
- </asp:TemplateField>
- </Columns>
- <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
- <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
- <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
- <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" Width="100px" />
- <EditRowStyle BackColor="#2461BF" />
- <AlternatingRowStyle BackColor="White" />
- </asp:GridView>
- </div>
- </form>
- </body>
- </html>
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public int Total { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
System.Data.DataTable dtItems = new System.Data.DataTable();
dtItems.Columns.Add("ItemName", typeof(string));
dtItems.Columns.Add("Price", typeof(int));
dtItems.Rows.Add("Bike", 350);
dtItems.Rows.Add("Cell Phones", 200);
dtItems.Rows.Add("Book", 35);
Total = Convert.ToInt32(dtItems.Compute("Sum(Price)", null));
//Binding gridview
grvItems.DataSource = dtItems;
grvItems.DataBind();
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grvItems" runat="server" ShowFooter="True"
AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333"
GridLines="None">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:BoundField FooterText="Total" DataField="ItemName" HeaderText="Item" />
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<%# Eval("Price")%>
</ItemTemplate>
<FooterTemplate>
<%= Total %>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" Width="100px" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>
DataTable.Compute("AggregateFunction(DataColumn)", "condition|Nothing|null")
The Compute() method is passed two arguments in a comma-separated list of string values. The first argument is the name of an AggregateFunction() which has the name of a DataColumn included within paretheses; this is the DataSet column to which the aggregate function is applied. The second argument restricts the DataRows that are accessed. If all rows of the column are used in the function, there are no restrictions, so a null value (or the keyword Nothing) is passed. Otherwise, a condition is supplied to identify which rows are selected.
Available aggregate functions include those shown in the following table.
- · Avg() The average of values in a column
- · Count() The number of rows (values) in a column
- · Max() The largest value in a column
- · Min() The smallest value in a column
- · StDev() The standard deviation of values in a column
- · Sum() The sum of values in a column
- · Var() The statistical variance of values in a column
More info:
DataTable.Compute method http://msdn.microsoft.com/enus/library/system.data.datatable.compute.aspx
To get the full source code click here.
Question 3: How to display client date time?
Each user wants to see the date and time adapted to his time zone. I'll show you how to display the client-side date and time directly in the page using JavaScript. I will also show you how to store the time offset and how to use it in my TimeZoneManager helper class to display server date time adapted to the client.
To display client date and time directly in the page:
- protected void Page_Load(object sender, EventArgs e)
- {
-
- this.ClientScript.GetPostBackEventReference(this, string.Empty);
-
- if (this.IsPostBack)
- {
- string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];
- string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];
-
- if (eventTarget == "GetTimeStartupScript")
- {
- this.Response.Write("Client-side time: ->" + eventArgument + "<-<br>");
- }
- }
- else
- {
- System.Text.StringBuilder javaScript = new System.Text.StringBuilder();
-
- javaScript.Append("var todaysDate = new Date();\n");
- javaScript.Append("var monthValue = todaysDate.getMonth() + 1;\n");
- javaScript.Append("var dayValue = todaysDate.getDate();\n");
- javaScript.Append("var yearValue = todaysDate.getFullYear();\n");
- javaScript.Append("var hoursValue = todaysDate.getHours();\n");
- javaScript.Append("var minutesValue = todaysDate.getMinutes();\n");
- javaScript.Append("var secondsValue = todaysDate.getSeconds();\n");
- javaScript.Append("var eventArgument = monthValue + '/' + dayValue + '/' + yearValue + ' ' + hoursValue + ':' + minutesValue + ':' + secondsValue;\n");
- javaScript.Append("__doPostBack('GetTimeStartupScript', eventArgument);\n");
-
- this.ClientScript.RegisterStartupScript(this.GetType(), "GetTimeStartupScript", javaScript.ToString(), true);
- }
- }
-
- protected void SaveDateTimeOffset(object sender, EventArgs e)
- {
- Session["TimeOffset"] = hidTimeOffset.Value;
- Response.Redirect("~/Q3Server.aspx");
- }
protected void Page_Load(object sender, EventArgs e)
{
// Insure that the __doPostBack() JavaScript method is created...
this.ClientScript.GetPostBackEventReference(this, string.Empty);
if (this.IsPostBack)
{
string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];
string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];
if (eventTarget == "GetTimeStartupScript")
{
this.Response.Write("Client-side time: ->" + eventArgument + "<-<br>");
}
}
else
{
System.Text.StringBuilder javaScript = new System.Text.StringBuilder();
javaScript.Append("var todaysDate = new Date();\n");
javaScript.Append("var monthValue = todaysDate.getMonth() + 1;\n");
javaScript.Append("var dayValue = todaysDate.getDate();\n");
javaScript.Append("var yearValue = todaysDate.getFullYear();\n");
javaScript.Append("var hoursValue = todaysDate.getHours();\n");
javaScript.Append("var minutesValue = todaysDate.getMinutes();\n");
javaScript.Append("var secondsValue = todaysDate.getSeconds();\n");
javaScript.Append("var eventArgument = monthValue + '/' + dayValue + '/' + yearValue + ' ' + hoursValue + ':' + minutesValue + ':' + secondsValue;\n");
javaScript.Append("__doPostBack('GetTimeStartupScript', eventArgument);\n");
this.ClientScript.RegisterStartupScript(this.GetType(), "GetTimeStartupScript", javaScript.ToString(), true);
}
}
protected void SaveDateTimeOffset(object sender, EventArgs e)
{
Session["TimeOffset"] = hidTimeOffset.Value;
Response.Redirect("~/Q3Server.aspx");
}
To display server date and time adapted to the client using time offset:
1. Store time offset in session
- <%@ Page Language="C#" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <script runat="server">
-
- protected void SaveDateTimeOffset(object sender, EventArgs e)
- {
- Session["TimeOffset"] = hidTimeOffset.Value;
- Response.Redirect("~/Q3Server.aspx");
- }
-
- </script>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
-
- <script type="text/javascript">
- function getLocalTimeOffset()
- {
- var now = new Date();
- var offset = now.getTimezoneOffset();
-
- var hidTimeZone = document.getElementById("<%= hidTimeOffset.ClientID %>");
- if(hidTimeZone != null)
- hidTimeZone.value = offset;
- }
-
- </script>
-
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:HiddenField runat="server" ID="hidTimeOffset" />
- <asp:Button runat="server" ID="btnSaveTimeOffsetInSession" Text="Save time offest in session"
- OnClientClick="return getLocalTimeOffset();" OnClick="SaveDateTimeOffset" />
- </div>
- </form>
- </body>
- </html>
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void SaveDateTimeOffset(object sender, EventArgs e)
{
Session["TimeOffset"] = hidTimeOffset.Value;
Response.Redirect("~/Q3Server.aspx");
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script type="text/javascript">
function getLocalTimeOffset()
{
var now = new Date();
var offset = now.getTimezoneOffset();
var hidTimeZone = document.getElementById("<%= hidTimeOffset.ClientID %>");
if(hidTimeZone != null)
hidTimeZone.value = offset;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:HiddenField runat="server" ID="hidTimeOffset" />
<asp:Button runat="server" ID="btnSaveTimeOffsetInSession" Text="Save time offest in session"
OnClientClick="return getLocalTimeOffset();" OnClick="SaveDateTimeOffset" />
</div>
</form>
</body>
</html>
2. Create the TimeZoneManager helper class to display the date
-
-
-
- public class TimeZoneManager
- {
-
-
-
-
-
-
- public static string DisplayDateTime(DateTime dateTime, double offset)
- {
- return DisplayDateTime(dateTime, offset, "dd-MMM-yyyy h:mm tt");
- }
-
-
-
-
-
-
-
-
- public static string DisplayDateTime(DateTime dateTime, double offset, string stringFormat)
- {
-
- DateTime utcDateTime = dateTime.ToUniversalTime();
-
- DateTime resultDateTime = utcDateTime.AddMinutes((-1) * offset);
-
- double hour = (((-1) * offset) / 60) - 1;
-
-
- return resultDateTime.ToString(stringFormat, new System.Globalization.CultureInfo("en-US"));
- }
- }
/// <summary>
/// Summary description for TimeZoneManager
/// </summary>
public class TimeZoneManager
{
/// <summary>
/// Displays the date time.
/// </summary>
/// <param name="dateTime">The date time.</param>
/// <param name="offset">minutes different to standard time.</param>
/// <returns></returns>
public static string DisplayDateTime(DateTime dateTime, double offset)
{
return DisplayDateTime(dateTime, offset, "dd-MMM-yyyy h:mm tt");
}
/// <summary>
/// Displays the date time.
/// </summary>
/// <param name="dateTime">The date time.</param>
/// <param name="offset">minutes different to standard time.</param>
/// <param name="stringFormat">String to format the date.</param>
/// <returns></returns>
public static string DisplayDateTime(DateTime dateTime, double offset, string stringFormat)
{
//Move to universal time (GMT) with Zero offset
DateTime utcDateTime = dateTime.ToUniversalTime();
//Add client side offset
DateTime resultDateTime = utcDateTime.AddMinutes((-1) * offset);
//DateTime resultDateTime = dateTime.AddHours(offset + 1);
double hour = (((-1) * offset) / 60) - 1;
//return string.Concat(resultDateTime.ToString(stringFormat, new System.Globalization.CultureInfo("en-US")), " ", resultDateTime.ToShortTimeString());
return resultDateTime.ToString(stringFormat, new System.Globalization.CultureInfo("en-US"));
}
}
3. Use this helper class
- <div>
- <%= TimeZoneManager.DisplayDateTime(DateTime.Now, Convert.ToDouble(Session["TimeOffset"]))%>
- </div>
<div>
<%= TimeZoneManager.DisplayDateTime(DateTime.Now, Convert.ToDouble(Session["TimeOffset"]))%>
</div>
To get the full source code click here.
Question 4: How to call javascript from server side (code behind)?
There are several ways to call the JavaScript from server-side (code behind).
By attaching a javascript event to a server control:
- btnJavascriptEventButton.Attributes.Add("onMouseOver", "alert('onMouseOver event');");
- btnJavascriptEventButton.Attributes.Add("onClick", "alert('click event');");
btnJavascriptEventButton.Attributes.Add("onMouseOver", "alert('onMouseOver event');");
btnJavascriptEventButton.Attributes.Add("onClick", "alert('click event');");
By using the RegisterStartupScript method:
-
- this.Page.ClientScript.RegisterStartupScript(typeof(Page), "ScriptAlertTest1", "alert('test1');", true);
-
- ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "ScriptAlertTest2", "alert('test2');", true);
//outside update panel
this.Page.ClientScript.RegisterStartupScript(typeof(Page), "ScriptAlertTest1", "alert('test1');", true);
//inside update panel
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "ScriptAlertTest2", "alert('test2');", true);
More info:
http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerclientscriptblock.aspx
http://msdn.microsoft.com/fr-fr/library/system.web.ui.scriptmanager.registerstartupscript.aspx
To get the full source code click here.
Question 5: What is the Difference between <% … %>, <%= … %>, <%# … %>, <%@ … %>, <%$ … %>?
Summary
· <% inline code %>
· <%=inline expression %>
· <%# data-binding expression %>
· <%@ directive %>
· <%-- commented out code or content --%>
· <%$ Resources:ClassKey, ResourceKey %>
<% inline code %>
Defines inline code that execute when the page is rendered. Use inline code to define self-contained code blocks or control flow blocks.
More info: http://msdn.microsoft.com/en-us/library/k6xeyd4z(VS.71).aspx
<%=inline expression %>
Defines inline expressions that execute when the page is rendered. Use inline expressions as a shortcut for calling the HttpResponse.Write method.
More info: http://msdn.microsoft.com/en-us/library/k6xeyd4z(VS.71).aspx
<%# data-binding expression %>
Data-binding expressions create bindings between any property on an ASP.NET page, including a server control property, and a data source when the DataBind method is called on the page. You can include data-binding expressions on the value side of an attribute/value pair in the opening tag of a server control or anywhere in the page.
More info: http://msdn.microsoft.com/en-us/library/bda9bbfx(VS.71).aspx
<%@ directive %>
Specifies settings used by the page and user control compilers when they processes ASP.NET Web Forms page (.aspx) and user control (.ascx) files.
|
@ Page
|
Defines page-specific attributes used by the ASP.NET page parser and compiler. Can be included only in .aspx files.
|
|
@ Control
|
Defines control-specific attributes used by the ASP.NET page parser and compiler. Can be included only in .ascx files (user controls).
|
|
@ Import
|
Explicitly imports a namespace into a page or user control.
|
|
@ Implements
|
Declaratively indicates that a page or user control implements a specified .NET Framework interface.
|
|
@ Register
|
Associates aliases with namespaces and class names, thereby allowing user controls and custom server controls to be rendered when included in a requested page or user control.
|
|
@ Assembly
|
Declaratively links an assembly to the current page or user control.
|
|
@ OutputCache
|
Declaratively controls the output caching policies of a page or user control.
|
|
@ Reference
|
Declaratively links a page or user control to the current page or user control.
|
More info: http://msdn.microsoft.com/en-us/library/xz702w3e(VS.71).aspx
<%-- commented out code or content --%>
Allows you to include code comments in the body of an .aspx file. Any content between opening and closing tags of server-side comment elements, whether ASP.NET code or literal text, will not be processed on the server or rendered to the resulting page.
More info: http://msdn.microsoft.com/en-us/library/4acf8afk(VS.71).aspx
<%$ Resources:ClassKey, ResourceKey %>
Contains the fields from a parsed resource expression.
More info: http://msdn.microsoft.com/en-us/library/system.web.compilation.resourceexpressionfields.aspx
To get the full source code click here.
Question 6: How to maintain scroll bar on postback?
When you use scrollbars it is interesting to maintain their position after the postback.
For pages it’s easy, you just have to put the page property MaintainScrollPositionOnPostback to true:
- <%@ Page Language="C#" MaintainScrollPositionOnPostback="true"%>
<%@ Page Language="C#" MaintainScrollPositionOnPostback="true"%>
But when you use a div, you have to save the position yourself for example via a hidden field. Here is an example to save the position:
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title>Untitled Page</title>
-
- <script type="text/javascript">
-
- // function saves scroll position
- function fScroll()
- {
- var hidScroll = document.getElementById("<%= hidScroll.ClientID %>");
- var divScroll = document.getElementById("<%= divScroll.ClientID %>");
- hidScroll.value = divScroll.scrollTop;
- }
-
- // function moves scroll position to saved value
- function fScrollMove()
- {
- var hidScroll = document.getElementById("<%= hidScroll.ClientID %>");
- document.getElementById("<%= divScroll.ClientID %>").scrollTop = hidScroll.value;
- }
-
- </script>
-
- </head>
- <body onload="fScrollMove();" onunload="document.forms(0).submit();">
- <form id="form1" runat="server">
- <div>
- <asp:HiddenField runat="server" ID="hidScroll" />
- <div runat="server" id="divScroll" style="overflow: scroll; width: 400; height: 200px;"
- onscroll="fScroll();">
- <p>
- Text here
- </p>
- </div>
- <asp:Button runat="server" ID="btnTest" Text="Maintain Scroll Position On Postback" />
- </div>
- </form>
- </body>
- </html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
// function saves scroll position
function fScroll()
{
var hidScroll = document.getElementById("<%= hidScroll.ClientID %>");
var divScroll = document.getElementById("<%= divScroll.ClientID %>");
hidScroll.value = divScroll.scrollTop;
}
// function moves scroll position to saved value
function fScrollMove()
{
var hidScroll = document.getElementById("<%= hidScroll.ClientID %>");
document.getElementById("<%= divScroll.ClientID %>").scrollTop = hidScroll.value;
}
</script>
</head>
<body onload="fScrollMove();" onunload="document.forms(0).submit();">
<form id="form1" runat="server">
<div>
<asp:HiddenField runat="server" ID="hidScroll" />
<div runat="server" id="divScroll" style="overflow: scroll; width: 400; height: 200px;"
onscroll="fScroll();">
<p>
Text here
</p>
</div>
<asp:Button runat="server" ID="btnTest" Text="Maintain Scroll Position On Postback" />
</div>
</form>
</body>
</html>
To get the full source code click here.
Question 7: How to use the enter key to submit a form?
One of the most frequent requests is using only keyboard for encoding. Here is a technique that allows you to submit a button by pressing enter.
- <%@ Page Language="C#" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <script runat="server">
- protected void Page_Load(object sender, EventArgs e)
- {
- RegisterSearchScript();
- }
-
- private void RegisterSearchScript()
- {
- StringBuilder sbScript = new StringBuilder();
- sbScript.Append("function " + this.ClientID + "submitSearch(e)\n");
- sbScript.Append("{\n");
- sbScript.Append("\tvar characterCode;\n");
- sbScript.Append("\tif(e && e.which){ //if which property of event object is supported (NN4)\n");
- sbScript.Append("\t\te = e;\n");
- sbScript.Append("\t\tcharacterCode = e.which; //character code is contained in NN4's which property\n");
- sbScript.Append("\t}\n");
- sbScript.Append("\telse{\n");
- sbScript.Append("\t\te = event;\n");
- sbScript.Append("\t\tcharacterCode = e.keyCode; //character code is contained in IE's keyCode property\n");
- sbScript.Append("\t}\n");
- sbScript.Append("\tif (characterCode == 13)\n");
- sbScript.Append("\t{\n");
- sbScript.Append("\tevent.cancelBubble = true;\n");
- sbScript.Append("\tevent.returnValue = false;\n");
- sbScript.Append("\tdocument.getElementById('" + btnSearch.ClientID + "').click();\n");
- sbScript.Append("\t}\n");
- sbScript.Append("}\n");
- if (!this.Page.ClientScript.IsClientScriptBlockRegistered("searchJSKey"))
- {
- this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "searchJSKey", sbScript.ToString(), true);
- }
- txtSearch1.Attributes.Add("onkeypress", this.ClientID + "submitSearch(event)");
- txtSearch2.Attributes.Add("onkeypress", this.ClientID + "submitSearch(event)");
- }
-
- protected void btnSearch_Click(object sender, EventArgs e)
- {
- lblDisplayInfo.Text = String.Format("Info: \nSearch 1: {0}\nSearch 2: {1}", txtSearch1.Text, txtSearch2.Text);
- }
- </script>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:TextBox ID="txtSearch1" runat="server"></asp:TextBox>
- <asp:TextBox ID="txtSearch2" runat="server"></asp:TextBox>
- <asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
- <asp:Label ID="lblDisplayInfo" runat="server" Text="Info:"></asp:Label>
- </div>
- </form>
- </body>
- </html>
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
RegisterSearchScript();
}
private void RegisterSearchScript()
{
StringBuilder sbScript = new StringBuilder();
sbScript.Append("function " + this.ClientID + "submitSearch(e)\n");
sbScript.Append("{\n");
sbScript.Append("\tvar characterCode;\n");
sbScript.Append("\tif(e && e.which){ //if which property of event object is supported (NN4)\n");
sbScript.Append("\t\te = e;\n");
sbScript.Append("\t\tcharacterCode = e.which; //character code is contained in NN4's which property\n");
sbScript.Append("\t}\n");
sbScript.Append("\telse{\n");
sbScript.Append("\t\te = event;\n");
sbScript.Append("\t\tcharacterCode = e.keyCode; //character code is contained in IE's keyCode property\n");
sbScript.Append("\t}\n");
sbScript.Append("\tif (characterCode == 13)\n");
sbScript.Append("\t{\n");
sbScript.Append("\tevent.cancelBubble = true;\n");
sbScript.Append("\tevent.returnValue = false;\n");
sbScript.Append("\tdocument.getElementById('" + btnSearch.ClientID + "').click();\n");
sbScript.Append("\t}\n");
sbScript.Append("}\n");
if (!this.Page.ClientScript.IsClientScriptBlockRegistered("searchJSKey"))
{
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "searchJSKey", sbScript.ToString(), true);
}
txtSearch1.Attributes.Add("onkeypress", this.ClientID + "submitSearch(event)");
txtSearch2.Attributes.Add("onkeypress", this.ClientID + "submitSearch(event)");
}
protected void btnSearch_Click(object sender, EventArgs e)
{
lblDisplayInfo.Text = String.Format("Info: \nSearch 1: {0}\nSearch 2: {1}", txtSearch1.Text, txtSearch2.Text);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtSearch1" runat="server"></asp:TextBox>
<asp:TextBox ID="txtSearch2" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
<asp:Label ID="lblDisplayInfo" runat="server" Text="Info:"></asp:Label>
</div>
</form>
</body>
</html>
To get the full source code click here.
Question 8: How to call page methods from client side using ajax.net?
1. In your script manager, set EnablePageMethods property to true.
2. Your code behind methods has to be static and preceded by the attribute [System.Web.Services.WebMethod()]
3. Call your page method as a web service
- <%@ Page Language="C#" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <script runat="server">
- [System.Web.Services.WebMethod()]
- public static string MyPageMethod(string value)
- {
- if (value.ToLower() == "test")
- return "test found!";
- return String.Format("{0} not found!", value);
- }
- </script>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
- </asp:ScriptManager>
-
- <script type="text/javascript">
- function callPageMethod() {
- PageMethods.MyPageMethod($get('<%= txtSearch.ClientID %>').value, onSucceeded, onFailed);
- }
- function onSucceeded(result, userContext, methodName) {
- $get('<%= lblInfo.ClientID %>').innerHTML = result;
- }
- function onFailed(error, userContext, methodName) {
- alert("An error occurred")
- }
- </script>
-
- Type "test" to found something:
- <asp:TextBox runat="server" ID="txtSearch"></asp:TextBox>
- <asp:Button runat="server" ID="btnCallPageMethod" Text="Search" OnClientClick="callPageMethod();return false;" />
- <asp:Label ID="lblInfo" runat="server"></asp:Label>
- </div>
- </form>
- </body>
- </html>
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
[System.Web.Services.WebMethod()]
public static string MyPageMethod(string value)
{
if (value.ToLower() == "test")
return "test found!";
return String.Format("{0} not found!", value);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<script type="text/javascript">
function callPageMethod() {
PageMethods.MyPageMethod($get('<%= txtSearch.ClientID %>').value, onSucceeded, onFailed);
}
function onSucceeded(result, userContext, methodName) {
$get('<%= lblInfo.ClientID %>').innerHTML = result;
}
function onFailed(error, userContext, methodName) {
alert("An error occurred")
}
</script>
Type "test" to found something:
<asp:TextBox runat="server" ID="txtSearch"></asp:TextBox>
<asp:Button runat="server" ID="btnCallPageMethod" Text="Search" OnClientClick="callPageMethod();return false;" />
<asp:Label ID="lblInfo" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
To get the full source code click here.
Question 9: How to capitalize each word in a string?
Finally, here is a simple method to capitalize each word in a string
- <script runat="server">
- static string CapitalizeString(System.Text.RegularExpressions.Match matchString)
- {
- string strTemp = matchString.ToString();
- strTemp = char.ToUpper(strTemp[0]) + strTemp.Substring(1, strTemp.Length - 1).ToLower();
- return strTemp;
- }
-
- protected void btnCapitalize_Click(object sender, EventArgs e)
- {
- lblResult.Text = System.Text.RegularExpressions.Regex.Replace(lblText.Text, @"\w+", new System.Text.RegularExpressions.MatchEvaluator(CapitalizeString));
- }
- </script>
<script runat="server">
static string CapitalizeString(System.Text.RegularExpressions.Match matchString)
{
string strTemp = matchString.ToString();
strTemp = char.ToUpper(strTemp[0]) + strTemp.Substring(1, strTemp.Length - 1).ToLower();
return strTemp;
}
protected void btnCapitalize_Click(object sender, EventArgs e)
{
lblResult.Text = System.Text.RegularExpressions.Regex.Replace(lblText.Text, @"\w+", new System.Text.RegularExpressions.MatchEvaluator(CapitalizeString));
}
</script>
To get the full source code click here.