Overview of Reporting with Visual Studio and Crystal Reports

Overview of Reporting with Visual Studio and Crystal Reports

8026EN

Being one of the reviewers of the book ‘Reporting with Visual Studio and Crystal Reports’ I would like to introduce you this book as a very good guide for those who want to create a reporting application from scratch using Visual Studio and Crystal Reports.

It is a step-by-step guide that goes beyond theory covering following points:

  • Letting you get hand-on experience.
  • Utilize a dataset and table adapter as data sources for your report.
  • Learn how to add reports to forms and pass parameters dynamically.

What you will learn from this book

  • Set up Microsoft Visual Studio, Crystal Reports, and Microsoft SQL server
  • Create a new reporting application
  • Design the application GUI
  • Connect to a database and use a dataset and table adapter
  • Add Crystal Reports to the application
  • Add database fields to the report and format them
  • Group and sort report data using parameter fields and special fields

In Detail

Reports are documents that present focused, salient content to a specific audience. Crystal Reports is a business intelligence application that will help you design and generate reports from a wide range of data sources. It helps you summarize a good deal of information in a visually appealing manner.

“Reporting with Visual Studio and Crystal Reports” is a practical, hands-on guide that will provide you with a number of clear, step-by-step exercises, and help you take advantage of the real power of Crystal Reports. This book will not only help you create effective reports, but also teach you how to create a reporting application.

“Reporting with Visual Studio and Crystal Reports” will guide you through the installation of Crystal Reports and Visual Studio. As you progress from one chapter to the next, you will gradually build a reporting application. You will also learn how to select the right data, and enhance your report by grouping and sorting data. This book will also help you create chart reports to improve your report design. With this book, you will learn how to create a complete reporting application and a wide variety of reports.

Approach

A fast-paced, example-based guide to learn how to create a reporting application using Visual Studio and Crystal Reports.

Who this book is for

“Reporting with Visual Studio and Crystal Reports” is for developers new to Crystal Reports. It will also prove useful to intermediate users who wish to explore some new techniques in Crystal Reports using Microsoft Visual Studio. Readers are expected to have basic knowledge of C#, Microsoft Visual Studio, and Structured Query Language (SQL).

Web URL

If you want to view more details about the book or want to place an order, please Click Here

Swf not working in Aspx page

Many of you might have come to a problem of Swf not working in Aspx page. You might have tried to embed flash object in the ASP.NET page but it doesn’t work even after modifying parameters. The same thing might be working in the simple HTML page but not in the ASP.NET.

Why?

Because most of the examples on internet shows the example as:

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="800" height="400" id="banner">
    <param name="movie" value="images/FileName.swf" />
    <param name="quality" value="high" />
    <embed src="images/FileName.swf" width="800" height="400" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
  </object>

It works in the simple HTML page, you run it, it works fine but when you put it in the ASPX page and try to run using the website URL, it doesn’t work

Actually the problem resides in the file path because you have to provide the relative path which can be accessed using the website URL.

So you can fix it by modifying the above code as mentioned below:

<object id="banner" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0"
                            width="800" height="400">
                            <param name="movie" value="http://localhost/WebsiteName/images/FileName.swf" />
                            <param name="quality" value="high" />                            
                            <embed src="http://localhost/WebsiteName/images/FileName.swf" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer"
                                type="application/x-shockwave-flash" width="800" height="400"></embed>
                        </object>

Enjoy!!!

Date format conversion

If you are tired of Date format conversion error because you have to take care of user locale settings and based on that you have to pasre the date to desired format using DateTime.Parse or Convert.ToDateTime methods. Still you can get error of “input string was not in correct format” so there is a way around to this problem. Below is the method which takes the source date, source format and returns you the destination format as specified in the parameters.

Have a look at that:

public static string GetFormattedDate(String SourceDate, string SourceDateFormat, string ReturnFormat)
    {
        string[] Params = new string[3];
        string sDate = "";
        string sMonth = "";
        string sYear = "";
        string DateSeparator = "/";

        if (SourceDate.Length > 1)
        {
            if (SourceDate.Length > 9)
            {
                SourceDate = SourceDate.Substring(0, 10);
            }
            else if (SourceDate.Length == 9)
            {
                SourceDate = SourceDate.Substring(0, 9);
            }

            SourceDate = SourceDate.Replace("-", "/");

            Params = SourceDate.ToString().Split(DateSeparator.ToCharArray());

            if (SourceDateFormat == "dd/mm/yyyy")
            {

                if (Params[0].Length == 1)
                    sDate = "0" + Params[0].ToString();
                else
                    sDate = Params[0];

                if (Params[1].Length == 1)
                    sMonth = "0" + Params[1].ToString();
                else
                    sMonth = Params[1];

                if (Params[2].Length == 1)
                    sYear = "0" + Params[2].ToString();
                else
                    sYear = Params[2].Substring(0, 4);

            }
            else if (SourceDateFormat == "mm/dd/yyyy")
            {
                if (Params[1].Length == 1)
                    sDate = "0" + Params[1].ToString();
                else
                    sDate = Params[1];

                if (Params[0].Length == 1)
                    sMonth = "0" + Params[0].ToString();
                else
                    sMonth = Params[0];

                if (Params[2].Length == 1)
                    sYear = "0" + Params[2].ToString();
                else
                    sYear = Params[2].Substring(0, 4);
            }

            switch (ReturnFormat)
            {
                case "dd/mm/yyyy":
                    return sDate + DateSeparator + sMonth + DateSeparator + sYear;

                case "mm/dd/yyyy":
                    return sMonth + DateSeparator + sDate + DateSeparator + sYear;

                default:
                    return "";
            }
        }
        else
        {
            return "";
        }
    }

Basically what it does is, it splits the date and manually formats the date accodring to the desired format.

So you can try it like this:

DateTime dtJoinDate = Convert.ToDateTime(GetFormattedDate(txtJoinDate.Text, "dd/mm/yyyy", "mm/dd/yyyy"));

Enjoy…

 

How to add processing div in web page

You might be wondering on How to add processing div in web page using jQuery in ASP.NET, this processing bar will be shown on each user action which is going back to server. You can download all the supporting files including javascript and images by clicking here, you may follow the steps below to add the processing div.

First of all you need to add the script reference to the some javascript files. There are multiple ways to add a reference.

1. If you are using Telerik then add a reference to your Telerik assembly on the page:

<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>

then put these lines in your page under ‘form’ tag.

<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>

then put these lines in your page under 'form' tag.

<telerik:RadScriptManager ID="ToolkitScriptManager1" runat="server" >
        <Scripts>
            <asp:ScriptReference Path="~/Scripts/ProgressScript.js" />
            <asp:ScriptReference Path="~/Scripts/jquery-1.4.1.min.js" />
        </Scripts>
    </telerik:RadScriptManager>

2. If you are using AjaxControlToolkit then add a reference to your AjaxControlToolkit assembly:

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

then put these lines in your page under ‘form’ tag.

<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        <Scripts>
            <asp:ScriptReference Path="~/Scripts/ProgressScript.js" />
        </Scripts>
    </cc1:ToolkitScriptManager>

now you need to define the div which will be displayed as a processing div.

<div id="pnlPopup" class="PrProgress" style="display: none;">
        <div id="innerPopup" class="PrContainer">
            <div class="PrHeader">
            
               <asp:Label ID="Label9" runat="server" Text="<%$ Resources:Language, PleaseWait %>" />
               
               </div>
            <div class="PrBody">
                <asp:Image runat="server" Width="220px" Height="19px" AlternateText="loading..."  ID="imgUpdateProgress" ImageUrl="~/images/activity.gif" />
                
            </div>
        </div>
    </div>

You might have notices that there are few CSS classes being used, they are described below:

.PrProgress
{
    display: block;
    position: absolute;
    padding: 2px 3px;
}
.PrContainer
{
    border: solid 1px #808080;
    border-width: 1px 0px;
}
.PrHeader
{
    background: url(../../Images/sprite.png) repeat-x 0px 0px;
    border-color: #808080 #808080 #ccc;
    border-style: solid;
    border-width: 0px 1px 1px;
    padding: 0px 10px;
    color: #000000;
    font-size: 9pt;
    font-weight: bold;
    line-height: 1.9;  
    white-space:nowrap;
    font-family: verdana,helvetica,clean,sans-serif;
}
.PrBody
{
    background-color: #f2f2f2;
    border-color: #808080;
    border-style: solid;
    border-width: 0px 1px;
    padding: 10px;
}
.PrIFrame
{
	
}

Now you need to call some javascript to make it function, add this javascript at the end of your page before “body” closing tag.

<script type="text/javascript">
        Sys.Application.add_load(applicationLoadHandler);
        Sys.Application.add_unload(applicationUnloadHandler);
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandler);
    </script>

Just run the page in the browser and see the difference on each server action.

How to download file using handler

Here is a detailed description on How to download file using handler. Also some tips on RadUpload custom validation.

You can use a generic handler to download files from server, it has the following advantages:

1. You can have download statistics.
2. You can track downloads.
3. You can implement download protection by putting extra authentication.
4 Download can be disallowed if required.

Lets say you have a RadUpload control on your page.

<telerik:RadUpload ID="rup_AttachedFiles" runat="server" ControlObjectsVisibility="RemoveButtons, AddButton" />

And you want to validate the files on the client side which are being uploaded,
so add a custom validator:

<asp:customvalidator id="CustomValidator1" runat="server" validationgroup="frmInquiry"
    enabled="true" clientvalidationfunction="ValidateFileNames" errormessage="Please Upload a file or same file is being uploaded twice"
    text="*" display="None" />

Now you write the Client Validation Function for your custom validator:

<script type="text/javascript">
    function ValidateFileNames(Source, args) {
        var FilesValid = true;
        var AttachedFiles = new Array();
        var radUpload = $find('<%= rup_AttachedFiles.ClientID %>');
        var fileInputs = radUpload.getFileInputs();
        if ((fileInputs.length == 1) && (fileInputs[0].value == "")) {
            FilesValid = false;
        }
        else {
            var duplicateFieldFlag = false;
            for (var i = 0; i < fileInputs.length; i++) {
                var fileName = fileInputs[i].value.substring(fileInputs[i].value.lastIndexOf("\\") + 1, fileInputs[i].value.length);
                for (var j = 0; j < AttachedFiles.length; j++) {
                    if (fileName == AttachedFiles[j]) {
                        duplicateFieldFlag = true;
                        radUpload.clearFileInputAt(i);
                        fileInputs[i].focus();
                        break;
                    }
                }
                if (duplicateFieldFlag) {
                    FilesValid = false;
                    break;
                }
                if (fileInputs[i].value.length != 0) {
                    AttachedFiles[AttachedFiles.length] = fileName;
                }
            }
        }
        args.IsValid = FilesValid;

    }
</script>

I am not going into detail of how to upload it using RadUpload control. Its time to put a repeater control to show a list of already uploaded files from the server. Again I will not explain how to get the uploaded files information from DB and bind it to the repeater.

<asp:repeater id="rpAttach" runat="server" onitemdatabound="rpAttach_onItemDataBound">
    <HeaderTemplate>
       <table id="tbl1" cellpadding="0" cellspacing="0" border="0" width="100%">
         <tr>
          <td>
           <asp:Label runat="server" ID="lblAttachement" Text="File Name" />
          </td>
        </tr>
    </HeaderTemplate>
    <ItemTemplate>
      <tr>
       <td >
        <asp:LinkButton ID="lnkFileName" runat="server" ></asp:LinkButton>
       </td>
      </tr>
    </ItemTemplate>
    <SeparatorTemplate>
        <tr>
            <td>
                <hr />
            </td>
        </tr>
    </SeparatorTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
    </asp:repeater>

Now you have to define the event handler rpAttach_onItemDataBound for the event OnItemDataBound. Where you will bind the file name link to a javascript function. Which will show a Disclaimer text before downloading:

protected void rpAttach_onItemDataBound(object
    sender, RepeaterItemEventArgs e) 
    { 
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) 
        { 
            LinkButton aLinkFileName = (LinkButton)e.Item.FindControl("lnkFileName");
            Files sFile = ((Files)e.Item.DataItem); aLinkFileName.Text = sFile.FileName; aLinkFileName.Attributes.Add("OnClick","OpenDisclaimer('" + HttpUtility.UrlEncode(strBasePath) + "','" + HttpUtility.UrlEncode(sFile.FileName)+ "','" + ConfigurationManager.AppSettings["DisclaimerText"] + "')"); 
        } 
    }

Now put the disclaimer text in the web config file

<add key="DisclaimerText" value="The attachment contains confidential and proprietary information. You have abide by copyright laws. blah blah blah " />

Now we have to define the function OpenDisclaimer

<script type="text/javascript">
        function OpenDisclaimer(strFilePath, strFileName, strText) {
            strURL = 'Handlers/GetFile.ashx?FullPath=' + strFilePath + '&FileName=' + strFileName;
            var answer = confirm("Disclaimer: " + strText);
            if (answer) {
                window.location.href = strURL;
                return true;
            }
            else 
            return false;
        } 
    </script>

Now is the time to add the GetFile handler to your project. Below is the code for it. It recognizes the file type and puts the contents of file type into chunks by chunks to client. // Handlers/GetFile.ashx

<%@  WebHandler Language="C#" Class="GetFile" %>

    using System; 
    using System.Collections; 
    using System.Data; 
    using System.Linq; 
    using System.Web; 
    using System.Web.Services; 
    using System.Web.Services.Protocols; 
    using System.Xml.Linq; 
    using System.IO; 
    using System.Web.SessionState; 
    using System.Configuration;

    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 

    public class GetFile : IHttpHandler, IReadOnlySessionState
    { 
        public void ProcessRequest(HttpContext context) 
        { 
            try 
            { 
                string FilePath = context.Request.Params["FullPath"];
                string filename = context.Request.Params["FileName"]; 

                FilePath = HttpUtility.UrlDecode(FilePath);
                string fullPath = "\\FileServername\FolderName\" + FilePath + filename; 

                // "\\FileServername\FolderName\" you can keep this path in web config string extension = System.IO.Path.GetExtension(filename);

                if (extension == null) 
                    extension = ""; 
                extension = extension.Replace(".", "");

                string contentDisposition; 

                if (context.Request.Browser.Browser == "IE" && (context.Request.Browser.Version == "7.0" || context.Request.Browser.Version == "8.0")) 
                    contentDisposition = "attachment; filename=" + Uri.EscapeDataString(filename); 
                else if (context.Request.Browser.Browser == "Safari") 
                    contentDisposition = "attachment; filename=" + filename; 
                else 
                    contentDisposition= "attachment; filename*=UTF-8''" + Uri.EscapeDataString(filename); 

                context.Response.AddHeader("Content-Disposition",contentDisposition); 
                context.Response.ContentType = "Application/" + extension;

                System.IO.BinaryReader reader = new System.IO.BinaryReader(new System.IO.FileStream(fullPath,System.IO.FileMode.Open)); 

                //Sent the data in chunks of x byte int ChunkSize = 10000;
                byte[] buffer = new byte[ChunkSize]; 
                int idx = 0; 
                long size = 0; 

                //Write the file chunk by chunk. 

                while ((size = reader.Read(buffer, 0, ChunkSize)) == ChunkSize)
                { 
                    context.Response.BinaryWrite(buffer); 
                    idx += ChunkSize; 
                } 

                reader.Close(); 

                //Write the remaining bytes 
                if (size > 0) 
                { 
                    byte[] remaining = new byte[size]; Array.Copy(buffer, 0, remaining, 0, size); 
                    context.Response.BinaryWrite(remaining); 
                } 
            } 
            catch 
            { 
                context.Response.ContentType= "Application/html"; 
                context.Response.StatusCode = 404; 
                context.Response.StatusDescription = "File not found"; 
            } 
        } 
    }

Enjoyyyyyy!!!!

Compare date and time using RadDateTimePicker

After searching a lot I found the solution to compare date and time using RadDateTimePicker because it was not fulfilling my requirements. So if you are working with Telerik RadDateTimePicker and you want to compare date and time using RadDateTimePicker then you can use the following code:

Lets say you have following two RadDateTimePicker controls on your page for start date and end date:

This one

<telerik:RadDateTimePicker ID=”dpStartDateTime” runat=”server”>
<TimeView ID=”TimeView1″ Interval=”00:30:00″ runat=”server” StartTime=”07:30:00″>
</TimeView>
<DateInput ID=”DateInput1″ runat=”server”>
<ClientEvents OnLoad=”onLoadRadTimePicker1″></ClientEvents>
</DateInput>
</telerik:RadDateTimePicker>

and the other one

<telerik:RadDateTimePicker ID=”dpEndDateTime” runat=”server”>
<TimeView ID=”TimeView2″ Interval=”00:30:00″ runat=”server” StartTime=”07:30:00″>
</TimeView>
<DateInput ID=”DateInput2″ runat=”server”>
<ClientEvents OnLoad=”onLoadRadTimePicker2″></ClientEvents>
</DateInput>
</telerik:RadDateTimePicker>

Your RadDateTimePicker may have different properties for TimeView according to what you want to display in time picker.

Now you have to put the CustomValidator control on your page in order to do the validation for start and end date.

<asp:CustomValidator runat=”server” ID=”CustomValidator1″ Text=”*” Display=”dynamic”
EnableClientScript=”true” ClientValidationFunction=”compare” />

You can set the ValidateEmptyText=”false” in the above tag if you do not want to compare the empty text.

Also you can set the ValidationGroup=”YourValidationGroupName” in the above tag if you want to do the validation for specific group using specific button click.

Now you have to write your CustomValidator ClientValidationFunction which will do the validation and date time comparison.

<script type=”text/javascript”>

//<![CDATA[
var RadTimePicker1;
var RadTimePicker2;

function compare(sender, args) {
var Date1 = new Date(RadTimePicker1.get_selectedDate());
var Date2 = new Date(RadTimePicker2.get_selectedDate());

args.IsValid = true;
if ((Date2 – Date1) <= 0) {
alert(‘End date time must be greater than start date time’);
args.IsValid = false;
}
}

function onLoadRadTimePicker1(sender, args) {
RadTimePicker1 = sender;
}

function onLoadRadTimePicker2(sender, args) {
RadTimePicker2 = sender;
}
//]]>

</script>

Enjoyyyy!!!

Working with Anthem.NET

Anthem.NET is an open source cross platform AJAX toolkit for the ASP.NET 1.1 and 2.0 development environment. Anthem.NET controls library has built in AJAX functionality and all credit goes to Jason Diamond who had the great idea to encapsulate AJAX functionality into regular Web Form controls. By using the Anthem.NET controls we can get rid of the typical postbacks.

 

All you have to do is download the Anthem.NET project source code from the following URL:

 

http://anthemdotnet.com/downloads.aspx

 

This source code includes different projects for VS.NET 2003, 2005, Examples and Extensions.

 

There are multiple ways to include Anthem.NET into your project:

 

1) You can add a reference to your project by browsing to the Anthem-2005 (if we take an example to integrate the Anthem.NET in our VS.NET 2005 project) and open the file named ‘Anthem-2005.csproj’

 

2) Alternatively you can seperately compile the Anthem-2005, generate the dll, copy and place it in your bin directory.

 

Now what happens if we want to use those Anthem.NET controls to our ASP.NET Web Application.

 

First of all you have to register that Anthem assembly to your page using

 

<%@ Register TagPrefix=”anthem” Namespace=”Anthem” Assembly=”Anthem” %>

 

Add an anthem:Button to your page:

 

Add a label to your page that would be used to show the current time without a postback whenever the above button is clicked

The attribute ‘AutoUpdateAfterCallBack=”true”‘ updates the control after every callback

Now add an event handler attribute for button’s click as you do with your normal ASP.NET Button

Do necessary coding in the event handler

void btnDisplayTime_Click(object sender, EventArgs e)
{
lblDisplayTime.Text = DateTime.Now.ToString();
}

By running your web application you can see the result that the lable will be updated without having any postback. Working with Anthem.NET is as easy as your normal ASP.NET controls library.

There is a problem that sometimes when you want to use Response.Redirect with Anthem.NET Controls, it doesnt work, Jason Diamond has given a way around for this problem.

You can use the following line of code in order to change the location of window.

Anthem.Manager.AddScriptForClientSideEval(“window.location = ‘http://www.google.com’;”);

Waiting for your comments on this article

How to: use Infragistics UltraWebGrid RowEditTemplate using Javascript in ASP.NET 2.0 (C#)

Infragistics UltraWebGrid is an important tool in ‘NetAdvantage for ASp.NET’ Suite. UltraWebGrid has built in AJAX functionality, along with enhanced performance and improved GUI.

 

In this article we’ll learn how to use UltraWebGrid’s RowEditTemplate using JavaScript. But I’ll be showing the necessary code to be modified.

 

You have to register the assembly in the page you wish to use UltraWebGrid using ‘Register’ Tag

 

Then you have to add the UltraWebGrid to your page

 

<igtbl:ultrawebgrid id=”UWGItems” runat=”server” width=”100%” height=”150px” browser=”Xml” oninitializelayout=”UWGItems_InitializeLayout”></igtbl:ultrawebgrid>

 

In your codefile define the UWGItems_InitializeLayout method

 

protected void UWGItems_InitializeLayout(object sender, Infragistics.WebUI.UltraWebGrid.LayoutEventArgs e)

{

// The InitializeLayout event is called when the grid binds to data. Many of these

// settings can be set at design time, rather then run time, via the property window.

// For this sample, these properties are set in code so that the settings are more easily visible.

 

// Turn on addnew, update and delete for the grid

e.Layout.AllowAddNewDefault = AllowAddNew.Yes;

e.Layout.AllowUpdateDefault = AllowUpdate.Yes;

e.Layout.AllowDeleteDefault = AllowDelete.Yes;

 

//Add the AddNew button

e.Layout.AddNewBox.Hidden = false;

e.Layout.Bands[0].AddButtonCaption = “Add New”;

e.Layout.Bands[0].AddButtonToolTipText = “Click here to Add New.”;

 

 

//// The Primary key field in most cases is an autogenerated number and will not be updated or set by the user. This

//// will prevent user action to modify the value

e.Layout.Bands[0].Columns.FromKey(“Sr”).AllowUpdate = AllowUpdate.No;

 

//// The DataKeyField of the Band should be set to PrimaryKey of the underlying table. To set the DataK

e.Layout.Bands[0].DataKeyField = “Sr”;

 

 

}

 

In your page’s Page_load event you can bind the grid to any data source e.g.

 

this.UWGItems.DataSource = this.TempDt;

this.UWGItems.DataBind();

 

Assuming that we’ve four columns in TempDT:

1) Sr. Serial Number

2) ItemName

3) ItemCode

4) Amount

 

These columns will be shown in your UltraWebGrid along with the * with each row for row editing and an ‘Add New’ button at the bottom of the grid. By clicking on ‘*’ or ‘Add New’ Button will open up the RowEditTemplate which we’ll be using later in this article.

 

Define the RowEditTemplate for your UltraWebGrid by adding the following lines of code to your Grid HTML

 

<bands>

<igtbl:ultragridband>

<rowedittemplate>

<table border=”0″ width=”100%”>

<tbody><tr>

<td colspan=”2″ align=”center”>Item Description</td>

</tr>

<tr>

<td align=”right”>Item Name:</td>

<td align=”left”><input id=”tmplItemName” size=”50″

 

columnkey=”ItemName” type=”text”></td>

</tr>

<tr>

<td align=”right”>Code:</td>

<td align=”left”><input id=”tmplItemCode” disabled=”disabled”

 

value=”821311″ size=”8″ type=”text”></td>

</tr>

<tr>

<td align=”right”>Amount:</td>

<td align=”left”><input id=”tmplItemAmount” size=”18″

 

columnkey=”Amount” type=”text”></td>

</tr>

<tr>

<td>

</td>

<td align=”left”>

<input id=”igtbl_reOkBtn”

 

onclick=”ValidateTemplate();igtbl_gRowEditButtonClick(event);” style=”width: 67px;” value=”OK”

 

type=”button”>

<input id=”igtbl_reCancelBtn”

 

onclick=”igtbl_gRowEditButtonClick(event);” style=”width: 67px;” value=”Cancel”

 

type=”button”>

</td>

</tr>

</tbody></table>

</rowedittemplate>

</igtbl:ultragridband>

</bands>

 

You may wish to validate the boxes on OK button click, you can define your ValidateTemplate() function and put necessary code according to your requirements

 

The function call igtbl_gRowEditButtonClick(event); is UltraWebGrid’s built in call that will handle the ‘OK’ or ‘Cancel’ button click

 

In between your <displaylayout></displaylayout> tags, you’ve to add a line which describes some client side functions

 

<clientsideevents dblclickhandler=”DblClick” beforerowtemplateclosehandler=”BeforeRowTemplateClose”

 

afterrowtemplateclosehandler=”AfterRowTemplateClose”></clientsideevents>

 

What happens when a user double clicks on any row or item, our function will just return 1 without doing anything means that there would be no operation in that case

 

// called when a cell, row label, or column header is double clicked

function DblClick(tableName, itemName)

{

return 1;

}

 

Our Purpose is to handle the RowEditTemplate using javascript, This following function will be called just before the RowEditTemplate is being closed.

We’ll be showing the next serial id and code using javascript, rest of the columns will be mapped automatically

 

function BeforeRowTemplateClose(gridName,rowId,bSaveChanges)

{

if(bSaveChanges)

{

var ActiveRow = igtbl_getActiveRow(gridName);

var oGrid = igtbl_getGridById(gridName);

var MaxCount=0;

var arr = rowId.split(“_”);

var ActualRowID = arr[arr.length-1];

var RowsCounter = oGrid.Rows.length;

 

for(c = 0; c < RowsCounter; c++)

{

var row = oGrid.Rows.getRow(c);

var CounterCell = row.getCell(0);

if(CounterCell.getValue()!=null)

MaxCount=CounterCell.getValue();

else if(CounterCell.getValue()==null && ActualRowID!=c)

oGrid.Rows.remove(c);

}

if(ActiveRow != null)

{

// Obtain the Cell object for Sr Column and Update the Cell value

if(ActiveRow.getCell(0).getValue()==null)

ActiveRow.getCell(0).setValue(MaxCount+1);

// Obtain the Cell object for Code Column and Update the Cell value

ActiveRow.getCell(2).setValue(“821311”);

 

}

}

}

 

if(bSaveChanges):

OK button of RowEditTemplate is clicked

 

var ActiveRow = igtbl_getActiveRow(gridName);

Get the active row of grid by specifying grid name

 

var arr = rowId.split(“_”);

var ActualRowID = arr[arr.length-1];

Split the row ID and get the actual rowID

 

for(c = 0; c < RowsCounter; c++)

{

var row = oGrid.Rows.getRow(c);

var CounterCell = row.getCell(0);

if(CounterCell.getValue()!=null)

MaxCount=CounterCell.getValue();

else if(CounterCell.getValue()==null && ActualRowID!=c)

oGrid.Rows.remove(c);

}

Loop through the grid till the RowsCounter, traverse through each row go till the last row, get the SerialNumber value and assign it to MaxCount, if the CounterCell’s value is null then delete that un-necessary row

 

if(ActiveRow != null)

{

// Obtain the Cell object for Sr Column and Update the Cell value

if(ActiveRow.getCell(0).getValue()==null)

ActiveRow.getCell(0).setValue(MaxCount+1);

// Obtain the Cell object for Code Column and Update the Cell value

ActiveRow.getCell(2).setValue(“821311″);

 

}

Check if the ActiveRow is not null and active row’s cell 0 has null value then place the new SerialNumber by adding 1 to MaxCount we already calculated.

We may wish to display some static code to the ItemCode column, for that purpose we’ve to place that value to active row’s cell no. 2 which is the ItemCode column.

 

Now you may wish to display the total of amounts entered in the Amount column, for this you will be writing javascript

 

function ‘AfterRowTemplateClose’

function AfterRowTemplateClose(tableName,itemName)

{

var oGrid = igtbl_getGridById(tableName);

var RowsCounter = oGrid.Rows.length;

//loop through grid values to calculate the total

var Amount=0;

for(c = 0; c < RowsCounter; c++)

{

var row = oGrid.Rows.getRow(c);

if(row.getCell(1).getValue()!=null)

{

var AmountCellVal = row.getCell(3).getValue();

Amount += parseInt(GetAmount(AmountCellVal));

}

}

// Obtain the txtTotalAmount textbox and update its value

document.getElementById(‘<%=txtTotalAmount.ClientID.ToString()%>”).value=Amount;

}

 

Get the grid using

var oGrid = igtbl_getGridById(tableName);

Get the row counte using

var RowsCounter = oGrid.Rows.length;

Loop through the grid, find the last column of the grid which is infact the amount column, add all the amounts

for(c = 0; c < RowsCounter; c++)

{

var row = oGrid.Rows.getRow(c);

if(row.getCell(1).getValue()!=null)

{

var AmountCellVal = row.getCell(3).getValue();

Amount += parseInt(GetAmount(AmountCellVal));

}

}

 

// Obtain the txtTotalAmount textbox and update its value

document.getElementById(‘<%=txtTotalAmount.ClientID.ToString()%>”).value=Amount;

 

Waiting for your comments on this article

How to format currency value entered in a text box using Javascript and ASP.NET

You might be in a situation where you want to display the value entered by user in a proper currency format e.g. if user entered 10000 and you want to format it like 10,000. In order to do so you’ve to follow these steps:

 

First add a text box in your asp.net page/control

 

<asp:TextBox ID=”txtTotal_Amount” runat=”server”></asp:TextBox>

 

Then add an attribute for OnKeyUp and OnKeyPress events

 

txtTotal_Amount.Attributes.Add(“OnKeyUp”, “OnCurrencyValueKeyUp(this);”);

txtTotal_Amount.Attributes.Add(“OnKeyPress”, “OnCurrencyValueKeyUp(this);”);

 

Now you’ve to define the function OnCurrencyValueKeyUp in order to handle the formatting

 

function OnCurrencyValueKeyUp(input)

{

if(input.value.toString().length == 1 && input.value.toString() == ‘0’)

input.value = input.value.replace(‘0’,”);

 

var num = input.value.replace(‘.’,”);

num = input.value.replace(/,/g,”);

if((!isNaN(num)|| num==’-‘) && num != ‘-0’)

{

if(num.indexOf(‘.’) > -1)

{

num = num.split(‘.’);

num[0] = num[0].toString().split(”).reverse().join(”).replace(/(?=d*.?)(d{3})/g,’$1,’).split(”).reverse().join(”).replace(/^[,]/,”);

if(num[1].length > 2)

{

num[1] = num[1].substring(0,num[1].length-1);

}

input.value = num[0]+’.’+num[1];

}

else

{

input.value = num.toString().split(”).reverse().join(”).replace(/(?=d*.?)(d{3})/g,’$1,’).split(”).reverse().join(”).replace(/^[,]/,”) };

}

else

{

input.value = input.value.substring(0,input.value.length-1);

}

input.value = input.value.toString().replace(/$| /g,”);

input.value = input.value.toString().replace(‘.’,”);

input.value = input.value .toString().replace(‘-,’,’-‘);

 

}

 

That’s it, just run your application and try it. Waiting for your comments on this article

How to restrict HTML/Javascript tags using Javascript and ASP.NET

There is a security threat that people use scripting tags into the input fields in order to hack/malfunction the application, you may use the steps described below in order to restrict the user not to enter these kind of tags:

 

Add a text box in your asp.net page/control

 

<asp:TextBox ID=”txtComments” runat=”server”></asp:TextBox>

 

Then add an attribute for OnClick and OnKeyPress events

 

txtComments.Attributes.Add(“OnClick”, “return RestrictHTMLTags();”);

 

Now you’ve to define the function RestrictHTMLTags in order to restrict the HTML tags

 

function RestrictHTMLTags()

{

txt_box=document.getElementsByTagName(‘INPUT’);

for (txt_0=0; txt_0 < txt_box.length; txt_0++)

{

if (txt_box[txt_0].type==’text’)

{

var str1=parseInt(txt_box[txt_0].value.indexOf(‘<‘))

var str2=parseInt(txt_box[txt_0].value.indexOf(‘>’))

if (str1 >= 0 || str2 >= 0 )

{

alert(“HTML or JavaScript tags are not allowed”)

txt_box[txt_0].value=”;

txt_box[txt_0].focus();

return false;

}

}

}

return true;

}

 

That’s how you restrict the user not to enter the restricted tags. Waiting for your comments on this article