Sunday, May 8, 2011

Javascript Confirm alert and fetch its value..

Hi guys...

Here is a simple javascript to display a confirm alert box and fetch its value..
you can simply perform other operations regarding the value that has been selected.













Hope this helps...

Saturday, May 7, 2011

Javascript alert from codebehind

Hi Guys,

I have made a class which will allow to popup a message box easily in web pages.
Just include this class in your application.

"Alert.cs"


using
System.Web;
using System.Text;
using System.Web.UI;

///
/// A JavaScript alert
///

public static class Alert
{

///
/// Shows a client-side JavaScript alert in the browser.
///

/// The message to appear in the alert.
public static void Show(string message)
{
// Cleans the message to allow single quotation marks
string cleanMessage = message.Replace("'", "\\'");
string script = "";

// Gets the executing web page
Page page = HttpContext.Current.CurrentHandler as Page;

// Checks if the handler is a Page and that the script isn't allready on the Page
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
}
}
}

Now just call it from any page by using

Add.Show(Message that you want to print);

eg. Add.Show("Hello");

Hope this will help you and make your work easy...

Monday, April 25, 2011

.NET Date Format Conversion in Oracle Format

Hey guys...recently i was facing a small problem of converting the system date to the format that oracle accepts..Oracle date is format sensitive.

.NET has the format 'mm-dd-yyyy' and oracle has the format 'dd-MMM-yy'

So I passed the System.datetime.now as parameter _date.

Then we just need to do this..

string _str = _date.ToString("dd-MMM-yy");

_str has the value in format "dd-MMM-yy"

and to all of those who don't kow that oracle accepts date as a parameter in quotes.

eg. '21-APR-11'

I hope this helps...

Sunday, April 10, 2011

Removing Thousand and Decimal From a Numeric Field In Crystal Report


Hi guys,

Recently I faced a problem in crystal report where i had to convert a mobile no filed into the numeric field which should not have thousand and decimals in crystal report.

My field was coming from database. I just simply did this

Step -1) Right click on the field to which you want to perform the operation and click on Format object





Step-2) Now a format editor opens as shown in the figure and click on the button that is right alongside the "Display String"






















Step - 3) Now opens the formula workshop...select the field in the first column from one of the three columns on the right side.

now at the bottom space write down the formula

Replace (cstr({Field Name},0,''),',' ,'')

all the thousand and decimals would be gone now..enjoy..




hope it will help you...!! :)

Friday, April 8, 2011

Multicolumn Primary key and Creating An Autonumber Field in Oracle

Hey guys...recently i faced this situation where i had to make two columns' combination a primary key in oracle and i found out the solution...

1 ) when creating a table

CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
)

2) when you have to alter table

ALTER TABLE Persons
ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

This way you can make two columns's combination a primary key


and now to make a field auto number in oracle...

step 1) create a table

SQL> create table sample (
2 no number not null,
3 description varchar2(200),
4 constraint pk_sample primary key(no)
5 );

Table created.

step 2)
Create a sequence object using the following code:

SQL> create sequence seq_sampleno
2 minvalue 1
3 start with 1
4 increment by 1;

Sequence created.


Step 3

Create a BEFORE INSERT trigger on sample table. Why BEFORE INSERT event? Because we need to take a sequence object’s value and then assign the value into a :new.no reference before Oracle actually insert a new record on sample table. Here is the code:

SQL> create or replace trigger tr_bi_sample
2 before insert on sample
3 for each row
4 begin
5 select seq_sampleno.nextval into :new.no from dual;
6 end;
7 /

Trigger created.


Step 4

Now, insert some new records into sample table using the following code:

SQL> insert into sample(description) values('First description');

1 row created.

SQL> insert into sample(description) values('Second description');

1 row created.

SQL> insert into sample(description) values('Third description');

1 row created.

To see the result, you can write the following code:

SQL> col no format 999 heading 'NO'
SQL> col description format A45 heading 'DESCRIPTION'
SQL> select * from sample;


Here is the result of that code:

NO DESCRIPTION
---- ---------------------------------------------
1 First description
2 Second description
3 Third description


I hope this helps you guys....!! :)

Monday, April 4, 2011

How to call Server Side function from Client Side Code using PageMethods in ASP.NET AJAX

You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX, and the easiest way out, is to use the ASP.NET AJAX Extensions.

One option while using Microsoft ASP.NET AJAX is to call ASP.NET Web services (.asmx files) from the browser by using client script. The script can call a webservice containing server-based methods (Web methods) and invoke these methods without a postback and without refreshing the whole page. However this approach could be overkill sometimes, to perform the simplest of tasks. Moreover the logic needs to be kept in a separate .asmx file. We need something that is more ‘integrated’ with our solution.

The option we are going to use in this article involves PageMethods. A PageMethod is basically a public static method that is exposed in the code-behind of an aspx page and is callable from the client script. PageMethods are annotated with the [WebMethod] attribute. The page methods are rendered as inline JavaScript.

Let us explore PageMethods with an example. The example we will be discussing here may not be the best example to explain PageMethods, but it will give you an idea of how to call server side code from client side. In this example, we will be connecting to the Customers table in the Northwind database. We will have some textboxes which will accept the CustomerID and in turn return the Contact Name of that Customer. The method returning ContactName will be called whenever the textbox loses focus. We will be using the onblur event where a javascript code will take in the value(CustomerID) from the textbox. This javascript function will then call a PageMethod (server side code) which returns the ContactName without any page refresh.
I assume that you have downloaded and installed ASP.NET AJAX extensions for ASP.NET 2.0. If not, I would advise you to download the extensions from here and install it before moving ahead. At any point of time, if you find a difficulty in understanding the code, download the sample project attached with this article at the end.

Step 1: Create an ASP.NET AJAX enabled website. Go to File > New > Website > ASP.NET AJAX-Enabled Web Site. Give the solution a name and location and click Ok.

Step 2: Drag and drop 2 labels and 4 textbox controls. We will be accepting the CustomerID from the user in the 2 textboxes and displaying the ‘ContactName’ in the other two textboxes. The textboxes that will display ‘ContactName’ has some properties set that will make it appear as a label without a border. Just set the BorderStyle=None, BorderColor=Transparent and ReadOnly=True. The markup will look similar to the following:


<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<div>
<asp:Label ID="lblCustId1" runat="server" Text="Customer ID 1">asp:Label>
<asp:TextBox ID="txtId1" runat="server">asp:TextBox><br />
<asp:TextBox ID="txtContact1" runat="server" BorderColor="Transparent" BorderStyle="None"
ReadOnly="True">asp:TextBox><br />
<br />
<asp:Label ID="lblCustId2" runat="server" Text="Customer ID 2">asp:Label>
<asp:TextBox ID="txtId2" runat="server">asp:TextBox><br />
<asp:TextBox ID="txtContact2" runat="server" BorderColor="Transparent" BorderStyle="None"
ReadOnly="True">asp:TextBox> <br />
div>
form>

Before moving ahead, we will store our connection string information in the Web.config. Add the following tag below your tag. Remember we have created an ‘ASP.NET AJAX enabled website’. The tag along with some other tags automatically get added to the web.config.


<connectionStrings>
<removename="all"/>
<addname="NorthwindConnectionString"connectionString="Data Source=(local); Initial Catalog=Northwind; Integrated Security = SSPI;"/>
connectionStrings>

Step 3: Currently we will add a method, ‘GetContactName()’ which will accept a CustomerID and return the Contact Name information from the Northwind database, Customer table. We will then transform this method as a PageMethod.
C#

public static string GetContactName(string custid)
{
if (custid == null || custid.Length == 0)
return String.Empty;
SqlConnection conn = null;
try
{
string connection = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
conn = new SqlConnection(connection);
string sql = "Select ContactName from Customers where CustomerId = @CustID";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("CustID", custid);
conn.Open();
string contNm = Convert.ToString(cmd.ExecuteScalar());
return contNm;
}
catch (SqlException ex)
{
return "error";
}
finally
{
conn.Close();
}
}

VB.NET

Public Shared Function GetContactName(ByVal custid As String) As String
If custid Is Nothing OrElse custid.Length = 0 Then
Return String.Empty
End If
Dim conn As SqlConnection = Nothing
Try
Dim connection As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString
conn = New SqlConnection(connection)
Dim sql As String = "Select ContactName from Customers where CustomerId = @CustID"
Dim cmd As SqlCommand = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("CustID", custid)
conn.Open()
Dim contNm As String = Convert.ToString(cmd.ExecuteScalar())
Return contNm
Catch ex As SqlException
Return "error"
Finally
conn.Close()
End Try
End Function

Step 4: We will now transform this method as a PageMethod and then call this method GetContactName() from client side code; i.e. using JavaScript. To enable the method as a PageMethod, add the attribute [WebMethod] on top of the method:
C#

[System.Web.Services.WebMethod]
public static string GetContactName(string custid)
{
}

VB.NET
_

_
Public Shared Function GetContactName(ByVal custid As String) As String
End Function

At the sametime, add the attribute EnablePageMethods="true" to the ScriptManager as shown below:

Step 5: Let us now create the JavaScript that will call this server side code. Add a javascript file called script.js to your solution (Right Click Project > Add New Item > Jscript File > Rename file to script.js). Add the following code to the javascript file.

function CallMe(src,dest)
{
var ctrl = document.getElementById(src);
// call server side method
PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);
}
// set the destination textbox value with the ContactName
function CallSuccess(res, destCtrl)
{
var dest = document.getElementById(destCtrl);
dest.value = res;
}
// alert message on some failure
function CallFailed(res, destCtrl)
{
alert(res.get_message());
}

Step 6: We now need to reference this JavaScript file from our aspx page and invoke the ‘CallMe()’ method whenever the textbox loses focus. To do so:
Add a reference to the javascript file in the body tag as shown below:

<body>
<script type="text/javascript" language="javascript" src="script.js"> script>
<form id="form1" runat="server">

………
Step 7: To invoke the methods whenever the textbox looses focus, add these lines of code in the Page_Load() event
C#
if (!Page.IsPostBack)
{
txtId1.Attributes.Add("onblur", "javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')");
txtId2.Attributes.Add("onblur", "javascript:CallMe('" + txtId2.ClientID + "', '" + txtContact2.ClientID + "')");
}

VB.NET

If (Not Page.IsPostBack) Then
txtId1.Attributes.Add("onblur", "javascript:CallMe('" & txtId1.ClientID & "', '" & txtContact1.ClientID & "')")
txtId2.Attributes.Add("onblur", "javascript:CallMe('" & txtId2.ClientID & "', '" & txtContact2.ClientID & "')")
End If

As shown above, we are using the Attributes.Add that lets us add an attribute to the server control’s System.Web.UI.AttributeCollection object. The function ‘CallMe’ kept in the ‘script.js’ file will be invoked. We are passing the source and destination textboxes as parameters. The source textbox will contain the CustomerID. The CustomerID will be looked up in the Customers table and the corresponding ‘ContactName’ will be retrieved in the destination textbox.
Well that is all that is needed to invoke server side code from client side. Run the code. Type ‘ALFKI’ in the first textbox and hit the tab key. You will see that the javascript function goes ahead and calls the PageMethod GetContactName() using PageMethods.GetContactName. It passes the value of the source textbox which contains the CustomerID. The ‘ContactName’ returned is displayed in the second textbox below the first one, in our case the value displayed is ‘Maria Anders’.
Troubleshooting: ‘PageMethods Is 'Undefined'’ error

1. Try setting EnablePageMethods="true" in the script manager tag

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>

2. Don't add the javascript references or code in the section. Add it to the tag.

<body>
<script type="text/javascript" language="javascript" src="script.js"> script>
<form id="form1" runat="server">
form>
body>
3. Page methods needs to be static in code behind.

I hope you have got an idea of how to call server side code using JavaScript. I have used this technique successfully in a few projects and just love and admire PageMethods.

If you want to return multiple values than put the return type as string array i.e. string[] and make the changes accordingly and set the textbox values in callsuccess function of javascript

Wednesday, March 16, 2011

Oracle Date insert problem

Recently I was working with Oracle Database and I found that ASP.NET Datetime causes problem as a date parameter in insert query as Oracle only takes the date value as a parameter but ASP.NET passes the Date and the Time both.

So to solve this, as a simple method i used to split the date into string format by space character i.e. (' ')

So you get the first parameter of the string array as date and other two as time.

eg.

string [] _str = Convert.ToString(_date).Split(' ');

string _strQuery = "insert into "+_strTableName+" values ('"+_name+"',"+Convert.ToDouble(_mobileno)+",'"+_company+"','"+_purpose+"','"+_department+"','"+_contactperson+"','"+_city+"','"+_str[0]+"','"+_entryperson+"','"+_exitperson+"','"+_status+"')";

return (ExecuteScalarWithPara(_strQuery));

So its just as simple as that and you are done with this problem

Monday, March 14, 2011

Class to convert Number to Gujarati

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace (Project Name)
{
public class NumberToGujarati
{
public String changeNumericToWords(double numb)
{
String num = numb.ToString();
return changeToWords(num, false);
}
public String changeCurrencyToWords(String numb)
{
return changeToWords(numb, true);
}
public String changeNumericToWords(String numb)
{
return changeToWords(numb, false);
}
public String changeCurrencyToWords(double numb)
{
return changeToWords(numb.ToString(), true);
}
private String changeToWords(String numb, bool isCurrency)
{
String val = "", wholeNo = numb, points = "", andStr = "", pointStr = "";
//String endStr = (isCurrency) ? ("Only") : ("");
String endStr = (isCurrency) ? ("Paura") : ("");
try
{
int decimalPlace = numb.IndexOf(".");
if (decimalPlace > 0)
{
wholeNo = numb.Substring(0, decimalPlace);
points = numb.Substring(decimalPlace + 1);
if (Convert.ToInt32(points) > 0)
{
andStr = (isCurrency) ? ("and") : ("point");// just to separate whole numbers from points/cents
//endStr = (isCurrency) ? ("Cents " + endStr) : ("");
endStr = (isCurrency) ? ("Paisa " + endStr) : ("");
pointStr = translateCents(points);
}
}
val = String.Format("{0} {1}{2} {3}", translateWholeNumber(wholeNo).Trim(), andStr, pointStr, endStr);
}
catch { ;}
return val;
}
private String translateWholeNumber(String number)
{
string word = "";
try
{
bool beginsZero = false;//tests for 0XX
bool isDone = false;//test if already translated
double dblAmt = (Convert.ToDouble(number));
double tm = (Convert.ToDouble(number));
int newnm = 0;
double rm = 0;
string strfst;
string tmpnumber = number.ToString();
//if ((dblAmt > 0) && number.StartsWith("0"))
if (dblAmt > 0)
{//test for zero or digit zero in a nuemric
beginsZero = number.StartsWith("0");

int numDigits = tmpnumber.Length;
int pos = 0;//store digit grouping
String place = "";//digit grouping name:hundres,thousand,etc...
switch (numDigits)
{
case 1://ones' range
word = ones(number);
isDone = true;
break;
case 2://tens' range
word = tens(number);
isDone = true;
break;
case 3://hundreds' range
rm = tm / 100;
newnm = (int)Math.Floor(rm);
pos = (numDigits % 3) + 1;
place = " so ";
//strfst = tmpnumber.Substring(0, pos);
//if (strfst == "2" || strfst == "02")
// place = " bso ";
//else
//if (newnm == 2)
//{
// place = " bso ";
//}
//else
//{
// if (strfst != "0")
// place = " so ";
//}

//if (newnm == 2)
//{
// number = tmpnumber.Substring(pos, tmpnumber.Length - 1);
//}
break;
case 4://thousands' range
case 5:
pos = (numDigits % 4) + 1;
strfst = tmpnumber.Substring(0, pos);
if (strfst != "0" && strfst != "00")
place = " H=r ";
//number = tmpnumber.Substring(pos, tmpnumber.Length - 1);
break;
case 6:
case 7://millions' range
pos = (numDigits % 6) + 1;
place = " Laaq ";
break;
case 8:
case 9:
pos = (numDigits % 8) + 1;
place = " kroD ";
break;
//add extra case options for anything above Billion...
default:
isDone = true;
break;
}
if (!isDone)
{//if transalation is not done, continue...(Recursion comes in now!!)

word = translateWholeNumber(number.Substring(0, pos)) + place + translateWholeNumber(number.Substring(pos));

//check for trailing zeros
//if (beginsZero) word = " and " + word.Trim();
if (beginsZero) word = " " + word.Trim();
}
//ignore digit grouping names
if (word.Trim().Equals(place.Trim())) word = "";
}
}
catch { ;}
return word.Trim();
}
private String tens(String digit)
{
int digt = Convert.ToInt32(digit);
String name = null;
switch (digt)
{
case 10:
name = "ds";//"Ten"
break;
case 11:
name = "Aigyar";//"Eleven"
break;
case 12:
name = "Baar";//"Twelve"
break;
case 13:
name = "Taer";//"Thirteen"
break;
case 14:
name = "CoEad";//"Fourteen"
break;
case 15:
name = "Pa>dr";//"Fifteen"
break;
case 16:
name = "Soa5";//"Sixteen"
break;
case 17:
name = "SaTtr";//"Seventeen"
break;
case 18:
name = "A!ar";//"Eighteen"
break;
case 19:
name = "Aog~aIs";//"Nineteen"
break;
case 20:
name = "vIs";
break;
case 21:
name = "AekvIs";
break;
case 22:
name = "BaavIs";
break;
case 23:
name = "TaevIs";
break;
case 24:
name = "covIs";
break;
case 25:
name = "pCcIs";
break;
case 26:
name = "0vIs";
break;
case 27:
name = "sTtavIs";
break;
case 28:
name = "A#avIs";
break;
case 29:
name = "Aog~at/Is";
break;
case 30:
name = " t/Is";
break;
case 31:
name = "Aet/Is";
break;
case 32:
name = "bt/Is";
break;
case 33:
name = "tet/Is";
break;
case 34:
name = "cot/Is";
break;
case 35:
name = "p>at/Is";
break;
case 36:
name = "0t/Is";
break;
case 37:
name = "Saa\\Dt/Is";
break;
case 38:
name = "AaDt/Is";
break;
case 39:
name = "Aog~acalIs";
break;
case 40:
name = "calIs";
break;
case 41:
name = "AektalIs";
break;
case 42:
name = "betalIs";
break;
case 43:
name = "tetalIs";
break;
case 44:
name = "cu>malIs";
break;
case 45:
name = "ipStalIs";
break;
case 46:
name = "0etalIs";
break;
case 47:
name = "suDtalIs";
break;
case 48:
name = "ADtalIs";
break;
case 49:
name = "Aog`pcas";
break;
case 50:
name = "pcas";
break;
case 51:
name = "Aekavn";
break;
case 52:
name = "Baavn";
break;
case 53:
name = "Taepn";
break;
case 54:
name = "copn";
break;
case 55:
name = "p>cavn";
break;
case 56:
name = "0Ppn";
break;
case 57:
name = "sTtavn";
break;
case 58:
name = "A#avn";
break;
case 59:
name = "Aog~asa[#";
break;
case 60:
name = "sa[#";
break;
case 61:
name = "Aeks#";
break;
case 62:
name = "Baas#";
break;
case 63:
name = "etes#";
break;
case 64:
name = "cos#";
break;
case 65:
name = "pa>s#";
break;
case 66:
name = "0as#";
break;
case 67:
name = "sDs#";
break;
case 68:
name = "ADs#";
break;
case 69:
name = "Ag`oisTter";
break;
case 70:
name = "isTter";
break;
case 71:
name = "{Kotr";
break;
case 72:
name = "Baaeter";
break;
case 73:
name = "Taoter";
break;
case 74:
name = "cumoter";
break;
case 75:
name = "p>coter";
break;
case 76:
name = "0oter";
break;
case 77:
name = "isTyotr";
break;
case 78:
name = "{#yotr";
break;
case 79:
name = "Ag~yaAe>sI";
break;
case 80:
name = "Ae>sI";
break;
case 81:
name = "AekyasI";
break;
case 82:
name = "ByasI";
break;
case 83:
name = "TyasI";
break;
case 84:
name = "coyaRsI";
break;
case 85:
name = "p>casI";
break;
case 86:
name = "0yasI";
break;
case 87:
name = "isTyasI";
break;
case 88:
name = "{#yasI";
break;
case 89:
name = "neVyasI";
break;
case 90:
name = "nev>u";
break;
case 91:
name = "Aeka`u>";
break;
case 92:
name = "Baa`u>";
break;
case 93:
name = "Taa`u>";
break;
case 94:
name = "Caora`u>";
break;
case 95:
name = "p>ca`u>";
break;
case 96:
name = "0Nnu>";
break;
case 97:
name = "sTta`u>";
break;
case 98:
name = "A#a`u>";
break;
case 99:
name = "nVva`u>";
break;

default:
if (digt > 0)
{
name = tens(digit.Substring(0, 1) + "0") + " " + ones(digit.Substring(1));
}
break;
}
return name;
}
private String ones(String digit)
{
int digt = Convert.ToInt32(digit);
String name = "";
switch (digt)
{
case 1:
name = "Aek";//"One"
break;
case 2:
name = "be";//"Two"
break;
case 3:
name = "t/~a";//"Three"
break;
case 4:
name = "Caar";//"Four"
break;
case 5:
name = "Pa>ac";//"Five"
break;
case 6:
name = "0";//"Six"
break;
case 7:
name = "Saat";//"Seven"
break;
case 8:
name = "Aa#";//"Eight"
break;
case 9:
name = "Nav";//"Nine"
break;
}
return name;
}
private String translateCents(String cents)
{
String cts = "", digit = "", engOne = "";
for (int i = 0; i < cents.Length; i++)
{
digit = cents[i].ToString();
if (digit.Equals("0"))
{
//engOne = "";
}
else
{
engOne = ones(digit);
}
cts += " " + engOne;
}
return cts;
}
}
}

Class to convert Number to English word

----Number to English class


using System;
namespace (Project Name)
{
public class NumberToEnglish
{
public String changeNumericToWords(double numb)
{
String num = numb.ToString();
return changeToWords(num, false);
}
public String changeCurrencyToWords(String numb)
{
return changeToWords(numb, true);
}
public String changeNumericToWords(String numb)
{
return changeToWords(numb, false);
}
public String changeCurrencyToWords(double numb)
{
return changeToWords(numb.ToString(), true);
}
private String changeToWords(String numb, bool isCurrency)
{
String val = "", wholeNo = numb, points = "", andStr = "", pointStr = "";
String endStr = (isCurrency) ? ("Only") : ("");
try
{
int decimalPlace = numb.IndexOf(".");
if (decimalPlace > 0)
{
wholeNo = numb.Substring(0, decimalPlace);
points = numb.Substring(decimalPlace + 1);
if (Convert.ToInt32(points) > 0)
{
andStr = (isCurrency) ? ("and") : ("Rupees And");// just to separate whole numbers from points/cents
//endStr = (isCurrency) ? ("Cents " + endStr) : ("");
endStr = (isCurrency) ? ("Paisa " + endStr) : ("");
pointStr = translateCents(points) + " Paisa";
}
}
val = String.Format("{0} {1}{2} {3}", translateWholeNumber(wholeNo).Trim(), andStr, pointStr, endStr);
}
catch { ;}
return val;
}
private String translateWholeNumber(String number)
{
string word = "";
try
{
bool beginsZero = false;//tests for 0XX
bool isDone = false;//test if already translated
double dblAmt = (Convert.ToDouble(number));
//if ((dblAmt > 0) && number.StartsWith("0"))
if (dblAmt > 0)
{//test for zero or digit zero in a nuemric
beginsZero = number.StartsWith("0");

int numDigits = number.Length;
int pos = 0;//store digit grouping
String place = "";//digit grouping name:hundres,thousand,etc...
switch (numDigits)
{
case 1://ones' range
word = ones(number);
isDone = true;
break;
case 2://tens' range
word = tens(number);
isDone = true;
break;
case 3://hundreds' range
pos = (numDigits % 3) + 1;
place = " Hundred ";
break;
case 4://thousands' range
case 5:
case 6:
pos = (numDigits % 4) + 1;
place = " Thousand ";
break;
case 7://millions' range
case 8:
case 9:
pos = (numDigits % 7) + 1;
place = " Million ";
break;
case 10://Billions's range
pos = (numDigits % 10) + 1;
place = " Billion ";
break;
//add extra case options for anything above Billion...
default:
isDone = true;
break;
}
if (!isDone)
{//if transalation is not done, continue...(Recursion comes in now!!)
word = translateWholeNumber(number.Substring(0, pos)) + place + translateWholeNumber(number.Substring(pos));
//check for trailing zeros
if (beginsZero) word = " and " + word.Trim();
}
//ignore digit grouping names
if (word.Trim().Equals(place.Trim())) word = "";
}
}
catch { ;}
return word.Trim();
}
private String tens(String digit)
{
int digt = Convert.ToInt32(digit);
String name = null;
switch (digt)
{
case 10:
name = "Ten";
break;
case 11:
name = "Eleven";
break;
case 12:
name = "Twelve";
break;
case 13:
name = "Thirteen";
break;
case 14:
name = "Fourteen";
break;
case 15:
name = "Fifteen";
break;
case 16:
name = "Sixteen";
break;
case 17:
name = "Seventeen";
break;
case 18:
name = "Eighteen";
break;
case 19:
name = "Nineteen";
break;
case 20:
name = "Twenty";
break;
case 30:
name = "Thirty";
break;
case 40:
name = "Fourty";
break;
case 50:
name = "Fifty";
break;
case 60:
name = "Sixty";
break;
case 70:
name = "Seventy";
break;
case 80:
name = "Eighty";
break;
case 90:
name = "Ninety";
break;
default:
if (digt > 0)
{
name = tens(digit.Substring(0, 1) + "0") + " " + ones(digit.Substring(1));
}
break;
}
return name;
}
private String ones(String digit)
{
int digt = Convert.ToInt32(digit);
String name = "";
switch (digt)
{
case 1:
name = "One";
break;
case 2:
name = "Two";
break;
case 3:
name = "Three";
break;
case 4:
name = "Four";
break;
case 5:
name = "Five";
break;
case 6:
name = "Six";
break;
case 7:
name = "Seven";
break;
case 8:
name = "Eight";
break;
case 9:
name = "Nine";
break;
}
return name;
}
private String translateCents(String cents)
{
String cts = "", digit = "", engOne = "";
for (int i = 0; i <>
{
digit = cents[i].ToString();
if (digit.Equals("0"))
{
engOne = "Zero";
}
else
{
engOne = ones(digit);
}
cts += " " + engOne;
}
return cts;
}
}
}

Printing using C#, Windows Application

A PrintDialog control is used to open the Windows Print Dialog and let user select the printer, set printer and paper properties and print a file. A typical Open File Dialog looks like Figure 1 where you select a printer from available printers, set printer properties, set print range, number of pages and copies and so on. Clicking on OK button sends the document to the printer.






Creating a PrintDialog

We can create a PrintDialog at design-time as well as at run-time.

Design-time

To create a PrintDialog control at design-time, you simply drag and drop a PrintDialog control from Toolbox to a Form in Visual Studio. After you drag and drop a PrintDialog on a Form, the PrintDialog looks like Figure 2.

PrintDlgImg2.jpg
Figure 2

Run-time

Creating a PrintDialog control at run-time is simple. First step is to create an instance of PrintDialog class and then call the ShowDialog method. The following code snippet creates a PrintDialog control.

PrintDialog PrintDialog1 = new PrintDialog();

PrintDialog1.ShowDialog();


Printing Documents


PrintDocument object represents a document to be printed. Once a PrintDocument is created, we can set the Document property of PrintDialog as this document. After that we can also set other properties. The following code snippet creates a PrintDialog and sends some text to a printer.


private void PrintButton_Click(object sender, EventArgs e)

{

PrintDialog printDlg = new PrintDialog();

PrintDocument printDoc = new PrintDocument();

printDoc.DocumentName = "Print Document";

printDlg.Document = printDoc;

printDlg.AllowSelection = true;

printDlg.AllowSomePages = true;

//Call ShowDialog

if (printDlg.ShowDialog() == DialogResult.OK)

printDoc.Print();

}


Summary

A PrintDialog control allows users to launch Windows Open File Dialog and let them select files. In this article, we discussed how to use a Windows Open File Dialog and set its properties in a Windows Forms application.