Wednesday, December 29, 2010

Multiple file upload in asp.net

This code show how to upload multiple file and save to database using asp.net and c#.
 HttpFileCollection hFileCollection = HttpContext.Current.Request.Files;  
for (int i = 0; i <= hFileCollection.Count; i++)
{
HttpPostedFile hPostedFile = hFileCollection[i];
if (hPostedFile.ContentLength > 0)
{
Stream fs = hFileCollection[i].InputStream;
int ImgLength = hFileCollection[i].ContentLength;
string contenttype = hFileCollection[i].ContentType;
string filePath = Path.GetFullPath(hFileCollection[i].FileName);
string filename = Path.GetFileName(filePath);
string extension = Path.GetExtension(hFileCollection[i].FileName).ToLower();
byte[] BinaryData = new byte[ImgLength];
int n = fs.Read(BinaryData, 0, ImgLength);
int DrawingID = objbztDrawingMasterBLL.CreateDrawingMaster(objbztDrawingMasterCls);
objbztDrawingMasterCls.DfileName = filename;
objbztDrawingMasterCls.FileConetentType = contenttype;
objbztDrawingMasterCls.FileData = BinaryData;
if (extension == ".doc" || extension == ".docx" || extension == ".xls" || extension == ".xlsx" || extension == ".jpg" || extension == ".png" || extension == ".gif" || extension == ".pdf")
{
string cmdstr = "INSERT INTO tblDtFiles(DID,DFileName,FileConetentType,FileData) VALUES(" + DID + "," + Convert.ToString(filename) + "," + Convert.ToString(contenttype) + "," + BinaryData + ")";
SqlHelper.ExecuteNonQuery(connectionString, CommandType.Text, cmdstr);
}
else
{
msg.Text = "Uploaded file should be doc/xls/jpg/png/gif/pdf...!";
}
}
}


Thanks & Regards
Santosh Singh

Thursday, October 21, 2010

Rounded off total income

Rounded off total income
       Int32 roundedAmt;  
Int32 torounded = Convert.ToInt32(lblTotalIncome.Text);
int lastdigit = torounded % 10;
if (lastdigit >= 5)
{
roundedAmt = torounded - lastdigit + 10;
}
else
{
roundedAmt = torounded - lastdigit;
}
lblRoundedOf.Text = Convert.ToString(roundedAmt);


Thanks & Regards
Santosh

Monday, October 11, 2010

Enable and disable textbox when checked the checkbox

Here code show how enable and disble textbox when user checked the textbox.
code disble the row which contain the textbox.you can also take only checkbox
to enable and disble not neccessary to disble row.

function showHide()
{

var chkSignature = document.getElementById('ctl00_ContentPlaceHolder1_tabContainer_pnl_chkSign');
var trsign = document.getElementById('ctl00_ContentPlaceHolder1_tabContainer_pnl_trsign');
if(chkSignature.checked)
{
if(trsign != null)
{
trsign.style.display = '';
}
}
else
{
if(trsign != null)
{
trsign.style.display = 'none';
}
}
}

<tr>
<td style="height: 22px; width: 180px;">
</td>
<td align="left" colspan="3" style="height: 22px; text-align: left">
<asp:CheckBox ID="chkSignature" runat="server" Text="Show Signature" onclick="showHide()"/>
</td>
</tr>
<tr id="trsign" runat="server" style="display:none">
<td style="height: 22px; width: 180px;">
</td>
<td align="left" colspan="3" style="height: 22px; text-align: left">
<asp:TextBox ID="txtSignature" runat="server" Width="350px" TextMode="MultiLine" ></asp:TextBox>
</td>
</tr>

Thanks & Regards
Santosh

Thanks & Regards
Santosh

Sunday, October 10, 2010

Bind DropDownList using SqlDataReader

This code pulling out data from a database into a data reader is as follows.
 protected void Page_Load(object sender, EventArgs e)  
{
if (!Page.IsPostBack)
{
bindDDL();
}
}
Public void bindDDL()
{
SqlConnection con =new SqlConnection(ConfigurationManager.
ConnectionStrings["ConnectionString"].ConnectionString.ToString();)
SqlCommand cmd=new SqlCommand();
cmd.connection=con;
con.open();
cmd.commandText="SELECT Citiid,CitiName FROM tableCity";
SqlDataReader dr;
dr=cmd.ExecuteReader();
ddlname.DataSource =dr;
ddlname.DataTextField = "CitiName";
ddlname.DataValueField = "Citiid";
ddlname.DataBind();
dr.close();
con.close();
}

Thanks & Regards
Santosh

Saturday, October 9, 2010

Get duplicated record from sql server table

Here query describes how to find duplicate record from a table in sql server

SELECT User_ID FROM tbl_Member
GROUP BY User_ID
HAVING count( * ) > 1

Thanks & Regards
Santosh Singh

Friday, October 1, 2010

Refresh the aspx page automatically

This small code refresh the aspx page automatically.
Set the time according to your requirment in content="time in sec".

<head runat="server">
<title>Untitled Page</title>
<meta http-equiv="refresh" content="20" />
</head>

Thursday, September 30, 2010

select data from one database and insert into another table

insert into tblMonthMst
select * from EMPMain.[dbo].[tblMonthMst]

Wednesday, September 29, 2010

Sql Server query Optimization

Optimization in Practice

Example 1:
I want to retrieve the name and salary of the employees of the R&D department.


Original:
Query : Select * From Employees
In Program : Add a filter on Dept or use command : if Dept = R&D--

Corrected :
Select Name, Salary From Employees Where Dept = R&D--

In the corrected version, the DB filters data because it filters faster than the program.
Also, you only need the Name and Salary, so only ask for that.
The data that travels on the network will be much smaller, and therefore your performances will improve.

Example 2 (Sorting):

Original:
Select Name, Salary
From Employees
Where Dept = 'R&D'
Order By Salary

Do you need that Order By Clause? Often, people use Order By in development to make sure returned data are ok; remove it if you don't need it.
If you need to sort the data, do it in the query, not in the program.

Example 3:
Original:
For i = 1 to 2000
Call Query : Select salary From Employees Where EmpID = Parameter(i)

Corrected:
Select salary From Employees Where EmpID >= 1 and EmpID <= 2000

The original Query involves a lot of network bandwidth and will make your whole system slow.
You should do as much as possible in the Query or Stored Procedure. Going back and forth is plain stupid.
Although this example seems simple, there are more complex examples on that theme.
Sometimes, the processing is so great that you think it's better to do it in the code but it's probably not.
Sometimes, your Stored Procedure will be better off creating a temporary table, inserting data in it and returning it than going back and forth 10,000 times.
You might have a slower query that saves time on a greater number of records or that saves bandwidth.

Example 4 (Weak Joins):
You have two tables Orders and Customers. Customers can have many orders.

Original:
Select O.ItemPrice, C.Name
From Orders O, Customers C

Corrected:
Select O.ItemPrice, C.Name
From Orders O, Customers C
Where O.CustomerID = C.CustomerID

In that case, the join was not there at all or was not there on all keys. That would return so many records that your query might take hours.
It's a common mistake for beginners.

Corrected 2:
Depending on the DB you use, you will need to specify the Join type you want in different ways.
In SQL Server, the query would need to be corrected to:

Select O.ItemPrice, C.Name
From Orders O INNER JOIN Customers C ON O.CustomerID = C.CustomerID

Choose the good join type (INNER, OUTER, LEFT, ...).
Note that in SQL Server, Microsoft suggests you use the joins like in the Corrected 2 instead of the joins in the Where Clause because it will be more optimized.

Example 5 (Weak Filters):
This is a more complicated example, but it illustrates filtering at its best.
We have two tables -- Products (ProductID, DescID, Price) and Description(DescID, LanguageID, Text). There are 100,000 Products and unfortunately we need them all.
There are 100 languages (LangID = 1 = English). We only want the English descriptions for the products.

We are expecting 100 000 Products (ProductName, Price).

First try:
Select D.Text As ProductName, P.Price
From Products P INNER JOIN Description D On P.DescID = D.DescID
Where D.LangID = 1

That works but it will be really slow because your DB needs to match 100,000 records with 10,000,000 records and then filter that Where LangID = 1.
The solution is to filter On LangID = 1 before joining the tables.

Corrected:
Select D.Text As ProductName, P.Price
From (Select DescID, Text From Description Where D.LangID = 1) D
INNER JOIN Products P On D.DescID = P.DescID

Now, that will be much faster. You should also make that query a Stored Procedure to make it faster.

Example 6 (Views):
Create View v_Employees AS
Select * From Employees

Select * From v_Employees

This is just like running Select * From Employees twice.
You should not use the view in that case.

If you were to always use the data for employees of R&D and would not like to give the rights to everyone on that table because of salaries being confidential,
you could use a view like that:

Create View v_R&DEmployees AS
Select Name, Salary From Employees Where Dept = 1
(Dept 1 is R&D).

You would then give the rights to View v_R&DEmployees to some people and would restrict the rights to Employees table to the DBA only.

That would be a possibly good use of views.

Tuesday, September 28, 2010

A field or property with the name 'CountryName' was not found on the selected data source.


Sol: In grid you have field but in not table.

Saturday, September 18, 2010

GridView with checkbox

This article is very simple.Many time developer need to how develop Gridview with checkbox,so we can select single or multiple record to update.
Javascript file
 <script language="javascript" type="text/javascript">  
function SelectAllCheckboxes(spanChk)
{
var oItem = spanChk.children;
var theBox=(spanChk.type=="checkbox")?spanChk:spanChk.children.item[0];
xState=theBox.checked;
elm=theBox.form.elements;
for(i=0;i if(elm[i].type=="checkbox" && elm[i].id!=theBox.id)
{
if(elm[i].checked!=xState)
elm[i].click();
}
}
</script>


Html code

 <form id="form1" runat="server">  
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="CustomerID" Width="366px" CellPadding="4" ForeColor="#333333" GridLines="None">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" InsertVisible="False" ReadOnly="True" SortExpression="PersonID" />
<asp:BoundField DataField="Fname" HeaderText="Fname" SortExpression="Fname" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
<HeaderTemplate>
<input id="chkAll" onclick="javascript:SelectAllCheckboxes(this);" runat="server" type="checkbox" />
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Delete" />
<asp:Label ID="lblmsg" runat="server" Text="Label" Visible="false"></asp:Label>
</form>


.cs code
 public partial class GridWithCheck : System.Web.UI.Page  
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["StrConnect"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
public void BindGridView()
{
SqlDataAdapter ad = new SqlDataAdapter("select * from tbl_CustomerDetail order by CustomerID", con);
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = ((CheckBox)(row.FindControl("chkSelect")));
if (cb != null && cb.Checked)
{
int custID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
string sqlstr = "delete from tbl_CustomerDetail where CustomerID='" + custID + "'";
SqlCommand mycmd;
mycmd = new SqlCommand(sqlstr, con);
con.Open();
mycmd.ExecuteNonQuery();
Page.RegisterStartupScript("pop", "&lt;script&gt;alert('Row deleted')&lt;/script&gt;");
BindGridView();
}
}
}
}

Thanks & Regards
Santosh

Friday, September 17, 2010

How to bind GridView with DataSet in ASP.Net and c#

  How to bind GridView with DataSet in ASP.Net and c#.  
  In this article I am using ASP.Net GridView control to display data from database.I am using Dataset to fill data and display in Grid.  
  protected void Page_Load(object sender, EventArgs e)   
  {   
       if (!Page.IsPostBack)   
       {   
           bindGridView();   
       }   
  }   
  public void bindGridView()   
  {   
       SqlConnection myconnection;   
       SqlCommand mycmd;   
       SqlDataAdapter myda;   
       DataSet ds;   
       myconnection = new SqlConnection("Data Source=YourServer;Initial Catalog=Test;Integrated Security=True");   
       myda = new SqlDataAdapter("Select * from tblCustDetail ", myconnection);   
       ds = new DataSet();   
       myda.Fill(ds);   
       gvCust.DataSource = ds;   
       gvCust.DataBind();   
  }  

Sql Server Interview Questions

1.What are the blocks in stored procedure
2. How do you handle exceptions. Give the syntax for it
3. What is normalization and types of normalization
4. When would you denormalize
5. Difference between a query and strored procedure
6. What is clustered and non-clustered indexes
7. Types of joins
8. How do you get all records from 2 tables. Which join do you use
9. Types of optimization
10. Difference between inline query and stored procedure
11. How do you rate yourrself in oracle and sql server
12. What is E-R diagram
13. Draw E-R diagram for many to many relationship
14. Design databaseraw er diagram for a certain scenario(many author many books)
15. Diff between primary key and unique key
16. What is Normalization
17. Difference between sub query and nested query
18. Indexes in oracle
19. Querry to retrieve record for a many to many relationship
20. Querry to get max and second max in oracle in one querry
21. Write a simple Store procedure and pass parameter to it
22. What are the types of triggers
23. Types of locks in database
24. Types of indexes. What is the default key created when a primary key is created in a table
25. What is clustered, non-clustured and unique index. How many indexes can be created on a table
26. Can we create non-clustured index on a clustered index
27. Types of backups
28. What is INSTEAD OF trigger
29. What is difference between triggers and stored procedures. And advantages of SP over triggers
30. What is DTS and purpose of DTS
31. Write a query to get 2nd maximum salary in an employee table Types of joins.
32. What is currency type in database
33. What are nested triggers
34. What is a heap related to database
35. Types of cursors and explanation each of them
36. Types of cursor locations and explanation on each of them
37. Types of cursor locks and explanation each of them
38 How do you retrieve set of records from database server.{Set max records = 100 & use paging where pager page no or records = 10 & after displaying 100 records
again connect to database retrieve next 100 }
39. How do you optimize SQL queries

Thanks & Regards
Santosh

Thursday, September 16, 2010

How to bind data to DropDownList in GridView in ASP.Net and C#

 How to bind data to DropDownList in GridView in ASP.Net and C#  
 In this article i am explaining how to bind data to DropDownList inside asp.net GridView control.  
 protected void GridDegree_RowDataBound(object sender, GridViewRowEventArgs e)  
 {  
      if (e.Row.RowType == DataControlRowType.DataRow)  
      {   
           DropDownList ddlDegreeType = (DropDownList)e.Row.FindControl("ddlDegreeType");  
           if (ddlDegreeType != null)  
           {  
                ddlDegreeType.DataSource = objDegreeDAL.GetDegree();   
                ddlDegreeType.DataBind();  
                ddlDegreeType.SelectedValue = dsDegree.Tables[0].Rows[e.Row.RowIndex]["DegreeId"].ToString();  
           }  
      }  
 }  
 .aspx page   
 <asp:TemplateField HeaderText="Degree Type>  
      <ItemTemplategt>  
           <asp:Label ID="lblDegreeType" runat="server" Text='<%# Bind("[Degree]") %></asp:Label>  
      </ItemTemplategt>  
      <EditItemTemplate>  
      <asp:DropDownList ID="ddlDegreeType" runat="server" DataTextField="Degree"  
      DataValueField="Degreeid>  
      </asp:DropDownList>  
      </EditItemTemplate>  
 </asp:TemplateField>  

Wednesday, September 15, 2010

Create pdf from GridView control in asp.net with c#

 Create pdf from GridView using asp.net with c#  
 Here this article show full code for create the pdf file from asp.net GridView.  
 Some time developer need how to do GridView to pdf .Here i have written the method according to my requirement.You can change according to your requirement and use this.  
 public void ConvertDataInPdf(DataTable dtExportInPdf, string reportName, string OtherInfo)  
 {  
      try  
      {  
           float CompanyNameSize = 11;  
           float ReportNameSize = 9;  
           float HeaderTextSize = 7;  
           float ReportTextSize = 6;  
           int totalWidth = 0;  
           int tableWidthPercent = 100;  
           int[] widths = new int[dtExportInPdf.Columns.Count];  
           for (int h = 0; h < dtExportInPdf.Columns.Count; h++) //Data table header column width  
           {  
                string strWidth = dtExportInPdf.Columns[h].ToString();  
                widths[h] = strWidth.Length;  
           }  
           foreach (DataRow dr in dtExportInPdf.Rows) //Data table column width  
           {  
                int[] colItemWidth = new int[dtExportInPdf.Columns.Count];  
                for (int i = 0; i < dtExportInPdf.Columns.Count; i++) //Data table max item width  
                {  
                     if (dr[i].ToString().Length > 20)  
                     {  
                          colItemWidth[i] = 20;  
                     }  
                     else if (dr[i].ToString().Length < 3)  
                     {  
                          colItemWidth[i] = 3;  
                     }  
                     else  
                     {  
                          colItemWidth[i] = dr[i].ToString().Length;  
                     }  
                     if (colItemWidth[i] > widths[i])  
                     {  
                          widths[i] = colItemWidth[i];  
                     }  
                }  
           }  
           for (int h = 0; h < dtExportInPdf.Columns.Count; h++)  
           {  
                totalWidth += widths[h];  
           }  
           Document pdfDoc = null;  
           if (totalWidth > 0 && totalWidth <= 110)  
           {  
                pdfDoc = new Document(PageSize.A4, 20, 20, 20, 20);  
           }  
           else if (totalWidth > 110 && totalWidth <= 160)  
           {  
                pdfDoc = new Document(PageSize.A4.Rotate(), 20, 20, 20, 20);  
           }  
           else if (totalWidth > 160 && totalWidth <= 250)  
           {  
                HeaderTextSize = 6;  
                ReportTextSize = 5;  
                pdfDoc = new Document(PageSize.LEGAL.Rotate(), 20, 20, 20, 20);  
           }  
           else if (totalWidth > 250 && totalWidth <= 300)  
           {  
                CompanyNameSize = 9;  
                ReportNameSize = 7;  
                HeaderTextSize = 6;  
                ReportTextSize = 5;  
                pdfDoc = new Document(PageSize.B1, 20, 20, 20, 20);  
           }  
           else if (totalWidth > 300)  
           {  
                CompanyNameSize = 9;  
                ReportNameSize = 7;  
                HeaderTextSize = 6;  
                ReportTextSize = 5;  
                pdfDoc = new Document(PageSize.B1.Rotate(), 20, 20, 20, 20);  
           }  
           // Creates a PdfPTable with column count of the table equal to no of columns of the datatable or gridview or gridview datasource.  
           PdfPTable pdfTable = new PdfPTable(dtExportInPdf.Columns.Count);  
           pdfTable.WidthPercentage = tableWidthPercent;  
           pdfTable.HeaderRows = 4; // Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.  
           #region PDFHeader  
           PdfPTable headerTable = new PdfPTable(3); // Creates a PdfPTable with 3 columns to hold the header in the exported PDF.  
           byte[] logo = (byte[])System.Web.HttpContext.Current.Session["Logo"];  
           iTextSharp.text.Image imgLogo = iTextSharp.text.Image.GetInstance(logo);  
           imgLogo.ScaleToFit(80f, 40f);//Resize image depend upon your need   
           imgLogo.SpacingBefore = 0f;//Give space before image   
           imgLogo.SpacingAfter = 1f;//Give some space after the image   
           PdfPCell clLogo = new PdfPCell(imgLogo);// Creates a PdfPCell which accepts a phrase as a parameter.  
           clLogo.Border = PdfPCell.NO_BORDER;// Sets the border of the cell to zero.  
           clLogo.HorizontalAlignment = Element.ALIGN_LEFT;// Sets the Horizontal Alignment of the PdfPCell to left.  
           clLogo.VerticalAlignment = Element.ALIGN_MIDDLE;  
           // Creates a phrase to hold the application name at the left hand side of the header.  
           Phrase phApplicationName = new Phrase("" + System.Web.HttpContext.Current.Session["CompanyName"] + "", FontFactory.GetFont("Arial", CompanyNameSize, iTextSharp.text.Font.NORMAL));  
           PdfPCell clApplicationName = new PdfPCell(phApplicationName);// Creates a PdfPCell which accepts a phrase as a parameter.  
           clApplicationName.Border = PdfPCell.NO_BORDER;// Sets the border of the cell to zero.  
           clApplicationName.HorizontalAlignment = Element.ALIGN_CENTER;// Sets the Horizontal Alignment of the PdfPCell to left.  
           clApplicationName.VerticalAlignment = Element.ALIGN_MIDDLE;  
           // Creates a phrase to show the current date at the right hand side of the header.  
           Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Arial", 7, iTextSharp.text.Font.NORMAL));  
           PdfPCell clDate = new PdfPCell(phDate);// Creates a PdfPCell which accepts the date phrase as a parameter.  
           clDate.HorizontalAlignment = Element.ALIGN_RIGHT;// Sets the Horizontal Alignment of the PdfPCell to right.  
           clDate.Border = PdfPCell.NO_BORDER;// Sets the border of the cell to zero.  
           clDate.VerticalAlignment = Element.ALIGN_MIDDLE;  
           headerTable.AddCell(clLogo);  
           headerTable.AddCell(clApplicationName);// Adds the cell which holds the application name to the headerTable.  
           headerTable.AddCell(clDate);// Adds the cell which holds the date to the headerTable.  
           headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;// Sets the border of the headerTable to zero.   
           // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.  
           PdfPCell cellHeader = new PdfPCell(headerTable);  
           cellHeader.VerticalAlignment = Element.ALIGN_TOP;  
           cellHeader.Border = PdfPCell.NO_BORDER;  
           cellHeader.Colspan = dtExportInPdf.Columns.Count;// Sets the column span of the header cell to noOfColumns.  
           pdfTable.AddCell(cellHeader);// Adds the above header cell to the table.  
           #endregion PDFHeader  
           //Creates a phrase for a new line.  
           Phrase phSpace1 = new Phrase("\n");  
           PdfPCell clSpace1 = new PdfPCell(phSpace1);  
           clSpace1.Border = PdfPCell.BOTTOM_BORDER;  
           clSpace1.BorderWidth = 1;  
           clSpace1.BorderColor = iTextSharp.text.Color.DARK_GRAY;  
           clSpace1.Colspan = dtExportInPdf.Columns.Count;  
           pdfTable.AddCell(clSpace1);  
           // Creates a phrase to hold the report name.  
           Phrase phHeader = new Phrase("" + reportName + "", FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.NORMAL));  
           PdfPCell clHeader = new PdfPCell(phHeader);  
           clHeader.Colspan = dtExportInPdf.Columns.Count;  
           clHeader.Border = PdfPCell.NO_BORDER;  
           clHeader.HorizontalAlignment = Element.ALIGN_CENTER;  
           clHeader.VerticalAlignment = Element.ALIGN_MIDDLE;  
           clHeader.PaddingTop = 5;  
           clHeader.PaddingBottom = 2;  
           pdfTable.AddCell(clHeader);  
           //Create Phrage to hold other informations  
           Phrase phOtherInfo = new Phrase(OtherInfo, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));  
           PdfPCell cellOtherInfo = new PdfPCell(phOtherInfo);  
           cellOtherInfo.Colspan = dtExportInPdf.Columns.Count;  
           cellOtherInfo.Border = Element.ALIGN_LEFT;  
           cellOtherInfo.PaddingBottom = 10;  
           pdfTable.AddCell(cellOtherInfo);  
           PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);  
           string strFooter = "Copyright © 2010 By Cnergee. Page:";  
           Phrase phCopyright = new Phrase(strFooter, FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8, iTextSharp.text.Font.NORMAL));  
           Phrase phPageNo = new Phrase("", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8, iTextSharp.text.Font.NORMAL));  
           HeaderFooter footer = new HeaderFooter(phCopyright, phPageNo);  
           //footer.Alignment = Element.ALIGN_LEFT;  
           footer.Alignment = Element.ALIGN_RIGHT;  
           footer.Border = iTextSharp.text.Rectangle.TOP_BORDER;  
           footer.GrayFill = 10;  
           pdfDoc.Footer = footer;  
           pdfDoc.Open();  
           Font font8 = FontFactory.GetFont("ARIAL Narrow", 7);  
           if (dtExportInPdf != null)  
           {  
                pdfDoc.Header = null;  
                //Create header for pdf table  
                string cloName = null;  
                Phrase ph = null;  
                for (int i = 0; i < dtExportInPdf.Columns.Count; i++)  
                {  
                     cloName = dtExportInPdf.Columns[i].ColumnName;  
                     if (dtExportInPdf.Columns.Count > 0)  
                     {  
                          ph = new Phrase(cloName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));  
                     }  
                     else  
                     {  
                          ph = new Phrase(cloName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));  
                     }  
                     pdfTable.AddCell(ph);  
                }  
                //Add data into the pdf table   
                for (int rows = 0; rows < dtExportInPdf.Rows.Count; rows++)  
                {  
                ph = null;  
                PdfPCell pCell = null;  
                for (int column = 0; column < dtExportInPdf.Columns.Count; column++)  
                {  
                     ph = new Phrase(dtExportInPdf.Rows[rows][column].ToString(), FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));  
                     pCell = new PdfPCell(ph);  
                     if (dtExportInPdf.Columns[column].ColumnName == "SrNo" || dtExportInPdf.Columns[column].ColumnName == "Sr.No." || dtExportInPdf.Columns[column].ColumnName == "Sr. No." || dtExportInPdf.Columns[column].ColumnName == "Code" || dtExportInPdf.Columns[column].ColumnName == "EmpCode" || dtExportInPdf.Columns[column].ColumnName == "EmployeeCode")  
                     {  
                          pCell.HorizontalAlignment = Element.ALIGN_CENTER;  
                     }  
                     else if (dtExportInPdf.Columns[column].ColumnName == "Amount")  
                     {  
                          pCell.HorizontalAlignment = Element.ALIGN_RIGHT;  
                     }  
                     else if (dtExportInPdf.Columns[column].ColumnName == "Date" || dtExportInPdf.Columns[column].ColumnName == "From" || dtExportInPdf.Columns[column].ColumnName == "To")  
                     {  
                          pCell.HorizontalAlignment = Element.ALIGN_CENTER;  
                     }  
                     else  
                     {  
                          pCell.HorizontalAlignment = Element.ALIGN_LEFT;  
                     }  
                     pdfTable.AddCell(pCell);  
                }  
                pdfTable.SetWidths(widths);  
                }  
                pdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table   
                pdfDoc.Add(pdfTable); // add pdf table to the document   
           }  
           pdfDoc.Close();  
           string pdfFileName = reportName;  
           reportName = reportName.Replace(" ", "");  
           System.Web.HttpContext.Current.Response.ContentType = "application/pdf";  
           System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename= " + pdfFileName + ".pdf");  
           System.Web.HttpContext.Current.Response.Write(pdfDoc);  
           System.Web.HttpContext.Current.Response.Flush();  
           System.Web.HttpContext.Current.Response.End();  
      }  
      catch (DocumentException de)  
      {  
           System.Web.HttpContext.Current.Response.Write(de.Message);  
      }  
      catch (IOException ioEx)  
      {  
           System.Web.HttpContext.Current.Response.Write(ioEx.Message);  
      }  
      catch (Exception ex)  
      {  
           System.Web.HttpContext.Current.Response.Write(ex.Message);  
      }  
 }  

Saturday, September 11, 2010

Bind dropdownlist default value

On RowDataBound
ddlCountry.SelectedValue = Ds.Tables[0].Rows[e.Row.RowIndex]["CountryId"].ToString();

On SelectedIndexChanged
ddlRGroup.SelectedValue = Ds.Tables[0].Rows[0]["RatingId"].ToString();

if (!Page.IsPostBack)
SqlDataReader dr = SqlHelper.ExecuteReader(connectionString, "tblFormula_Select", Convert.ToInt32(ViewState["CKFId"]), "S");
ddlTemp.SelectedValue = dr["TemplateId"].ToString();

Friday, September 10, 2010

Javascript validation for Gridview footer textbox

 Javascript validation for Gridview footer textbox  
 Here gridview have footer row that cantain dropdownlist and two textbox.This javascript validate these fields while inserting record in database.  
 function ValidateGrid()  
 {   
      ddlNewCountry = document.getElementById('<%=((DropDownList)gv.FooterRow.FindControl("ddlNewCountry")).ClientID%>');  
      txtNewEmpName = document.getElementById('<%=((TextBox)gv.FooterRow.FindControl("txtNewEmpName")).ClientID %>');  
      txtNewAge = document.getElementById('<%=((TextBox)gv.FooterRow.FindControl("txtNewAge")).ClientID %>');  
      if(ddlNewCountry.value == 0)  
      {  
           alert("Please Select Country...!");  
           ddlNewCountry.focus();  
           return false;  
      }  
      if(txtNewEmpName.value == 0)  
      {  
           alert("Please Enter Emp name...!");  
           txtNewEmpName.focus();  
           return false;  
      }  
      if(txtNewAge.value == 0)  
      {  
           alert("Please Enter age...!");  
           txtNewAge.focus();  
           return false;  
      }   
      return true;   
 }  

Javascript validation for Gridview in edit mode

 Javascript validation for Gridview textbox in edit mode  
 Clientside validation for Gridview textboxex while edting record.  
 Here gridview have dropdownlist and two textbox.This javascript clientside code validate these fields while edting record.   
 function ValidateGridEditMode()  
 {  
      var Gid = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer_gvCustomer').rows.length;  
      var i;  
      for(i=2; i <=Gid; i++)  
      {   
           if(i<10)  
           {  
                ddlCustLocation = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer_gvCustomer_ctl0'+i+'_ddlCustLocation');  
                txtCustCode = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer_gvCustomer_ctl0'+i+'_txtCustCode');  
                txtCustName = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer_gvCustomer_ctl0'+i+'_txtCustName');   
           }  
           else  
           {  
                ddlCustLocation = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer_gvCustomer_ctl'+i+'_ddlCustLocation');  
                txtCustCode = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer_gvCustomer_ctl'+i+'_txtCustCode');  
                txtCustName = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer_gvCustomer_ctl'+i+'_txtCustName');   
           }  
           ddlCustLocation != null || txtCustCode != null || txtCustName != null)  
           {  
                ddlCustLocation == 0)  
                {  
                     alert("Please Select Location..");  
                     ddlCustLocation.focus();  
                     return false;  
                }   
                else  
                {  
                     if(txtCustCode.value == 0)  
                     {  
                          alert("Please enter Customer Code..");   
                          txtCustCode.focus();   
                          return false;  
                     }   
                     else  
                     {  
                          if(txtCustName.value == "")  
                          {  
                               alert("Please enter Customer Name ..");   
                               txtCustName.focus();   
                               return false;  
                          }  
                     }   
                }   
           }   
      }  
      return true;  
 }  

Gridview control with Edit Delete and Update in ASP.NET using C#

 Gridview control with Edit Delete and Update in ASP.NET  
 Gridview Edit/Delete/Update using sqlhelper class and 3 layer architecture.  
 In this article I have tried to make the simple Add , Edit, Update and Delete functions in ASP.Net GridView.  
 Feature of this GridView  
 1.This example used three tier architecture.  
 2.Add new record using footer.  
 3.Update and delete record.  
 4.For edit and delete i have used image button for nice look.  
 5.If table is empty(No record in table) a blank dynamic Gridview display for with Add New buttion.  
 6.On Click Edit or Add New cursor focus to Textbox.  
 7.Auto Generated Serial Number In Gridview Control.  
 I have used property layer but i didnt write here,i think you can implement it according to your logic.  
 MySample.aspx page  
 <asp:GridView ID="GridViewEmpSkill" runat="server" AllowPaging="True" AutoGenerateColumns="False"  
 PageSize="12" OnPageIndexChanging="GridViewEmpSkill_PageIndexChanging" OnRowDataBound="GridViewEmpSkill_RowDataBound"  
 TabIndex="2" Width="697px" OnRowCancelingEdit="GridViewEmpSkill_RowCancelingEdit" OnRowEditing="GridViewEmpSkill_RowEditing"  
 OnRowUpdating="GridViewEmpSkill_RowUpdating" ShowFooter="True" OnRowCommand="GridViewEmpSkill_RowCommand"  
 OnRowDeleting="GridViewEmpSkill_RowDeleting" DataKeyNames="EmpSkillId">  
      <Columns>  
           <asp:TemplateField HeaderText="Sr No">  
                <ItemTemplate>  
                <asp:Label ID="lblSrNo" runat="server"></asp:Label>  
                </ItemTemplate>  
                <FooterTemplate>  
                <asp:Label ID="lblNewSrNo" runat="server"></asp:Label>  
                </FooterTemplate>  
                <ItemStyle HorizontalAlign="Center" Width="50px" />  
           </asp:TemplateField>  
           <asp:TemplateField HeaderText="EmpSkillId" Visible="False">  
                <ItemTemplate>  
                <asp:Label ID="lblEmpSkillId" runat="server" Text='<%# Bind("EmpSkillId") %>'></asp:Label>  
                </ItemTemplate>  
           </asp:TemplateField>  
           <asp:TemplateField HeaderText="EmpSkill">  
                <EditItemTemplate>  
                <asp:TextBox ID="txtEmpSkill" runat="server" Width="493px" BorderColor="White" BorderWidth="0px"  
                Height="14px" Text='<%# Bind("EmpSkill") %>'></asp:TextBox>  
                </EditItemTemplate>  
                <FooterTemplate>  
                <asp:TextBox ID="txtNewEmpSkill" runat="server" Width="493px" BorderColor="White" BorderWidth="0px"  
                Height="14px" Visible="false"></asp:TextBox>  
                </FooterTemplate>  
                <ItemTemplate>  
                <asp:Label ID="lblEmpSkill" runat="server" Text='<%# Bind("EmpSkill") %>'></asp:Label>  
                </ItemTemplate>  
                <FooterStyle HorizontalAlign="Left" />  
                <ItemStyle HorizontalAlign="Left" />  
           </asp:TemplateField>  
           <asp:TemplateField HeaderText="Activity">  
                <ItemTemplate>  
                <asp:ImageButton ID="imgEdit" runat="server" ImageUrl="~/Image/img_edit.png" CommandName="Edit" ToolTip="Edit" />  
                <asp:ImageButton ID="imgbtnDelete" runat="server" ImageUrl="~/Image/img_delete.png" ToolTip="Delete"  
                CommandName="Delete" OnClientClick="return ConfirmDelete();" />  
                </ItemTemplate>  
                <EditItemTemplate>  
                <asp:ImageButton ID="imgUpdate" runat="server" CausesValidation="True" CommandName="Update" ToolTip="Update"  
                ImageUrl="~/Image/update.png" Text="Update" />  
                <asp:ImageButton ID="imgCancel" runat="server" CausesValidation="False" CommandName="Cancel" ToolTip="Cancel"  
                ImageUrl="~/Image/cancel.png" Text="Cancel" />  
                </EditItemTemplate>  
                <FooterTemplate>  
                <asp:ImageButton ID="imgNewAdd" runat="server" ImageUrl="~/Image/row_add.png"  
                CommandName="AddNew" ToolTip="Add New" />  
                <asp:ImageButton ID="imgbtnNewInsert" runat="server" CausesValidation="True" CommandName="Insert" ToolTip="Save"  
                ImageUrl="~/Image/add.png" Visible="false" Text="Add" />  
                <asp:ImageButton ID="imgNewCancel" runat="server" CausesValidation="False" CommandName="Cancel" ToolTip="Cancel"  
                ImageUrl="~/Image/cancel.png" Visible="false" Text="Cancel" />  
                </FooterTemplate>  
                <FooterStyle HorizontalAlign="Center" Width="140px" />  
                <ItemStyle HorizontalAlign="Center" Width="140px" />  
           </asp:TemplateField>  
      </Columns>  
 </asp:GridView>  
 ===========  
 MySample.cs page  
 protected void GridViewEmployeeSkill()  
 {  
      try  
      {  
           Ds = SkillBLLobj.GetEmpSkillData();  
           if (Ds.Tables[0].Rows.Count > 0)  
           {  
                GridViewEmpSkill.DataSource = Ds;  
                GridViewEmpSkill.DataBind();  
           }  
           else  
           {  
                ShowNoResultFound(Ds,GridViewEmpSkill);  
                SrNoSkill = 1;  
           }  
      }  
      catch (Exception ex)  
      {  
           msgEmpSkill.Text = ex.Message;  
      }  
 }  
 protected void GridViewEmpSkill_RowEditing(object sender, GridViewEditEventArgs e)  
 {  
      GridViewEmpSkill.EditIndex = e.NewEditIndex;  
      GridViewEmpSkill();  
      GridViewEmpSkill.Rows[e.NewEditIndex].FindControl("txtEmpSkill").Focus();  
 }  
 protected void GridViewEmpSkill_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
 {  
      GridViewEmpSkill.EditIndex = -1;  
      GridViewSkill();  
 }  
 protected void GridViewEmpSkill_PageIndexChanging(object sender, GridViewPageEventArgs e)  
 {  
      GridViewEmpSkill.PageIndex = e.NewPageIndex;  
      GridViewSkill();  
 }  
 protected void GridViewEmpSkill_RowDataBound(object sender, GridViewRowEventArgs e)  
 {  
      if (e.Row.RowType == DataControlRowType.DataRow)  
      {  
           Label lblSrNo = (Label)e.Row.FindControl("lblSrNo");  
           lblSrNo.Text = SrNo.ToString();  
           SrNo++;   
      }  
 }  
 protected void GridViewEmpSkill_RowUpdating(object sender, GridViewUpdateEventArgs e)  
 {  
      try  
      {   
           SkillClsobj.SkillId = Convert.ToInt32(((Label)GridViewEmpSkill.Rows[e.RowIndex].FindControl("lblEmpSkillId")).Text);  
           SkillClsobj.Skill = Convert.ToString(((TextBox)GridViewEmpSkill.Rows[e.RowIndex].FindControl("txtEmpSkill")).Text);  
           int Update = SkillBLLobj.UpdateEmpSkill(SkillClsobj);  
           if (Update > 0)  
           {  
                msgEmpSkill.Text = "Record Updated Successfully !";  
                GridViewEmpSkill.EditIndex = -1;  
                GridViewSkill();  
           }  
      }  
      catch (Exception ex)  
      {  
           msgEmpSkill.Text = ex.Message.ToString();  
      }  
 }  
 protected void GridViewEmpSkill_RowCommand(object sender, GridViewCommandEventArgs e)  
 {  
      try  
      {  
      if (e.CommandName.Equals("AddNew") || e.CommandName.Equals("Insert"))  
      {  
      if (e.CommandName.Equals("AddNew"))  
      {  
      GridViewEmpSkill.EditIndex = -1;  
      GridViewSkill();   
      Label lblNewSrNo = (Label)GridViewEmpSkill.FooterRow.FindControl("lblNewSrNo");  
      lblNewSrNo.Text = SrNo.ToString();  
      ImageButton imgNewInsert = (ImageButton)GridViewEmpSkill.FooterRow.FindControl("imgNewInsert");  
      ImageButton imgNewCancel = (ImageButton)GridViewEmpSkill.FooterRow.FindControl("imgNewCancel");  
      ImageButton imgNewAdd = (ImageButton)GridViewEmpSkill.FooterRow.FindControl("imgNewAdd");  
      imgNewInsert.Visible = true;  
      imgNewCancel.Visible = true;  
      imgNewAdd.Visible = false;  
      TextBox txtNewEmpSkill = (TextBox)GridViewEmpSkill.FooterRow.FindControl("txtNewEmpSkill");  
      txtNewEmpSkill.Visible = true;  
      txtNewEmpSkill.Focus();  
      }  
      }  
      }  
      catch(Exception ex)  
      {  
      throw ex;  
      }  
      try  
      {  
           if (e.CommandName.Equals("Insert"))  
           {  
                ImageButton imgNewInsert = (ImageButton)GridViewEmpSkill.FooterRow.FindControl("imgNewInsert");  
                ImageButton imgNewCancel = (ImageButton)GridViewEmpSkill.FooterRow.FindControl("imgNewCancel");  
                ImageButton imgNewAdd = (ImageButton)GridViewEmpSkill.FooterRow.FindControl("imgNewAdd");  
                imgNewInsert.Visible = false;  
                imgNewCancel.Visible = false;  
                imgNewAdd.Visible = true;  
                TextBox txtNewSkill = (TextBox)GridViewEmpSkill.FooterRow.FindControl("txtNewEmpSkill");  
                txtNewEmpSkill.Visible = true;  
                txtNewEmpSkill.Focus();  
                SkillClsobj.Skill = Convert.ToString(((TextBox)GridViewEmpSkill.FooterRow.FindControl("txtNewSkill")).Text);  
                try  
                {  
                     if (SkillClsobj.Skill == "")  
                     {  
                          msgEmpSkill.Text = "Pleae Enter !";  
                     }  
                     else  
                     {  
                          int intResult= SkillBLLobj.InsertEmpSkill(SkillClsobj);  
                          if (intResult> 0)  
                          {  
                               msgEmpSkill.Text = "Record Added !";  
                               GridViewEmpSkill.EditIndex = -1;  
                               GridViewSkill();  
                          }  
                     }  
                }  
                catch (Exception ee)  
                {  
                     msgEmpSkill.Text = ee.Message.ToString();  
                }  
                finally  
                {  
                     SkillBLLobj = null;  
                }  
           }  
      }  
      catch(Exception ex)  
      {  
      throw ex;  
      }  
 }  
 protected void GridViewEmpSkill_RowDeleting(object sender, GridViewDeleteEventArgs e)  
 {  
      try  
      {  
           SkillClsobj.SkillId = (int)GridViewEmpSkill.DataKeys[e.RowIndex].Value;  
           int result = SkillBLLobj.DeleteSkill(SkillClsobj);  
           if (result > 0)  
           {  
                msgEmpSkill.Text = "Record Deleted Successfully !";  
                GridViewEmpSkill.EditIndex = -1;  
                GridViewSkill();  
           }  
      }  
      catch (Exception ex)  
      {  
           msgEmpSkill.Text = ex.Message.ToString();  
      }  
 }  
 private void ShowNoResultFound(DataSet ds,GridView gv)  
 {  
      DataTable dt = (DataTable)ds.Tables[0];  
      dt.Rows.Add(dt.NewRow());  
      gv.DataSource = dt;  
      gv.DataBind();  
      int TotalColumns = gv.Rows[0].Cells.Count;  
      gv.Rows[0].Cells.Clear();  
      gv.Rows[0].Cells.Add(new TableCell());  
      gv.Rows[0].Height = 0;  
      gv.Rows[0].Visible = false;  
 }  
 ======================  
 business logic layer  
 public class EmpSkillBLL  
 {  
      EmpSkillDAL SkillDALobj = new EmpSkillDAL();  
      public DataSet GetEmpSkillData()  
      {  
           try  
           {  
                return SkillDALobj.GetEmpSkillData();  
           }  
           catch  
           {  
                throw;  
           }  
      }  
      public int InsertSkill(EmpSkillCls objSkillCls)  
      {  
           try  
           {  
                return SkillDALobj.InsertEmpSkill(objSkillCls);  
           }  
           catch  
           {  
                throw;  
           }  
      }  
      public int UpdateSkill(EmpSkillCls objSkillCls)  
      {  
           try  
           {  
                return SkillDALobj.UpdateEmpSkill(objSkillCls);  
           }  
           catch  
           {  
                throw;  
           }  
      }  
      public int DeleteSkill(EmpSkillCls objSkillCls)  
      {  
           try  
           {  
                return objSkillDAL.DeleteEmpSkill(objSkillCls);  
           }  
           catch  
           {  
                throw;  
           }  
      }  
 }  
 ===========  
 data acess layer  
 public class EmpSkillDAL  
 {  
      SqlConnection conn = new SqlConnection("your connection string");  
      DataSet Ds = new DataSet();  
      public DataSet GetEmpSkillData()  
      {  
           Ds = SqlHelper.ExecuteDataset(conn, "sp_SelectDelete");  
           return Ds;  
      }  
      public int InsertEmpSkill(EmpSkillCls Emp)  
      {  
           try  
           {  
                int Insert = SqlHelper.ExecuteNonQuery(conn, "usp_EmpSkillMasterAddEdit", Emp.SkillId, Emp.Skill);  
                return Insert;  
           }  
           catch  
           {  
                throw;  
           }  
           finally  
           {  
                conn.Close();  
           }  
      }  
      public int UpdateEmpSkill(EmpSkillCls emp)  
      {  
           try  
           {  
                int Result = SqlHelper.ExecuteNonQuery(conn, "usp_EmpSkillMaster_AddEdit", Emp.SkillId, Emp.Skill);  
                return Result;  
           }  
           catch  
           {  
                throw;  
           }  
           finally  
           {  
                conn.Close();  
           }  
      }  
      public int DeleteEmpSkill(EmpSkillCls emp)  
      {  
           try  
           {  
                int result = SqlHelper.ExecuteNonQuery(conn, "usp_EmpSkillMasterSelect", emp.SkillId);  
                return result;  
           }  
           catch  
           {  
                throw;  
           }  
           finally  
           {  
                conn.Close();  
           }  
      }  
 }  

Onclick Gridview Select button fill all the data to textbox.

 Onclick Gridview Select button fill all the data to textbox.  
 All the textbox out of gridview.  
 protected void ImgSelect_Click(object sender, ImageClickEventArgs e)  
 {  
      ImageButton aspSender = sender as ImageButton;  
      Label Id = aspSender.FindControl("lblContId") as Label;  
      hdnId.Value = Id.Text;  
      DataSet dsContact = new DataSet();  
      dsContact = SqlHelper.ExecuteDataset(connectionString, "usp_GetContact", Convert.ToInt32(Id.Text.Trim()), EmpId, "S");  
      if (dsContact.Tables[0].Rows.Count != 0)  
      {  
           txtName.Text = dsContact.Tables[0].Rows[0]["Name"].ToString();  
           ddlRelation.SelectedValue = dsContact.Tables[0].Rows[0]["RelId"].ToString();   
           txtAddress.Text = dsContact.Tables[0].Rows[0]["Address"].ToString();  
      }  
 }  

Monday, September 6, 2010

Join Three Table

How to join three table
SELECT e.emp_name, d.DeptName
FROM Emp e INNER JOIN DeptName d
ON e.emp_id = d.emp_id JOIN Sal s
ON d.dept_id = s.dept_id


SELECT a.au_lname, a.au_fname, t.title
FROM authors a INNER JOIN titleauthor ta
ON a.au_id = ta.au_id JOIN titles t
ON ta.title_id = t.title_id

select
r.recipe_name,
i.ingredients_list,
p.products_list
from
recipes r,
ingredients i,
products p
where
r.RecipeID = i.IngreRecipeID and
i.IngreProductID = p.ProductID
;

How to Store Multiple Value In Session using asp.net c#

 How to Store Multiple Value In Session using asp.net c#  
 We can add multiple values by using class entiry or hashtable or arralist:  
 Here a we will use Hashtable for storing multiple value in session  
   
 Hashtable htEmpInfo = new Hashtable();  
   
 htEmpInfo.Add("Name", "Santosh");  
 htEmpInfo.Add("Designation", "SE");  
 htEmpInfo.Add("Department", "MS");  
   
 session["EmpDetails"]=htEmpInfo;  
   
 Retrieving the values from the session  
   
 Hashtable htEmpInformaiton = (Hashtable)session["EmpDetails"];  
 lblEmopName.Text=htEmpInformaiton["Name"].ToString();  
 lblDesignation.Text=htEmpInformaiton["Designation"].ToString();  

OnkeyPress attributes in TextBox using JavaScript

Here code shows how to use onkeypress in TextBox.When user write in textbox a Label show no. of charachter entered in TextBox

 function valid(txt,maxLen,lbl1)  
{
lbl1.innerText=(txt.value.length+1);
if(txt.value.length > (maxLen-1))
{
alert("Entered Text reach at its maximum size..!");
return false;
}
}
txtFeedback.Attributes["onkeypress"] = "return valid(this,500," + Label1.ClientID + ")";


Thanks & Regards
Santosh

Sunday, September 5, 2010

Gridview RowCommand

If you hav any button inside Gridview you handle that button under RowCommand like here Gridview have a Insert button inside Grid.

 protected void gvStuDetails_RowCommand(object sender, GridViewCommandEventArgs e)  
{
if (e.CommandName.Equals("Insert"))
{
objStuCls.StuId = Convert.ToInt32(((DropDownList)gvStuDetails.FooterRow.FindControl("ddlNewStuId")).SelectedValue);
objStuCls.StuName = Convert.ToString(((TextBox)gvStuDetails.FooterRow.FindControl("txtNewStuName")).Text);
try
{
int int = objClassMasterBLL.InsertClassMaster(objStuCls);
if (int > 0)
{
msgText = "Record Added Successfully !";
gvStuDetails.EditIndex = -1;
gvStu();
}
else
{
msg.Text = "This record already exists !";
}
}
catch (Exception ee)
{
msg.Text = ee.Message.ToString();
}
}
}

Thanks & Regards
Santosh

Saturday, September 4, 2010

Insert Images to SqlServer in ASP .NET

Here I am explaining how insert images into database using asp.net.

 protected void Button1_Click(object sender, EventArgs e)  
{
FileUpload fileUpload1 = ((FileUpload)(this.FindControl("fileUpload1")));
if (((fileUpload1.PostedFile == null) || (string.IsNullOrEmpty(fileUpload1.PostedFile.FileName) || (fileUpload1.PostedFile.InputStream == null))))
{
Label1.Text = "Please Upload Valid picture file";
return;
}
int len = fileUpload1.PostedFile.ContentLength;
byte[] pic = new byte[len];
fileUpload1.PostedFile.InputStream.Read(pic, 0, len);
string extension = System.IO.Path.GetExtension(fileUpload1.PostedFile.FileName).ToLower();
string MIMEType = null;
switch (extension)
{
case ".gif":
MIMEType = "image/gif";
break;
case ".jpg":
case ".jpeg":
case ".jpe":
MIMEType = "image/jpeg";
break;
case ".png":
MIMEType = "image/png";
break;
default:
Label1.Text = "Not a Valid file format";
return;
break;
}
string fname = txtName.Text;
string lname = txtLName.Text;
string gender = rdGender.SelectedItem.Text;
string age = drpAge.SelectedItem.Text;
string state = txtState.Text;
SqlConnection myConnection;
myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["StrConnectSan"].ToString());
SqlCommand myCommand = new SqlCommand("usp_InsertPersonDetail", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = fname;
myCommand.Parameters.Add("@LastName", SqlDbType.VarChar, 50).Value = lname;
myCommand.Parameters.Add("@GenderID", SqlDbType.VarChar, 50).Value = gender;
myCommand.Parameters.Add("@Age", SqlDbType.VarChar, 50).Value = age;
myCommand.Parameters.Add("@MCA", SqlDbType.VarChar, 50).Value = str;
myCommand.Parameters.Add("@State", SqlDbType.VarChar, 50).Value = state;
myCommand.Parameters.Add("@MIMEType", SqlDbType.VarChar, 50).Value = MIMEType;
myCommand.Parameters.Add("@ImageData",SqlDbType.Image,16).Value = pic;
myCommand.Parameters.Add("@Length", SqlDbType.VarChar, 50).Value = len;
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
msg.Text = "Record save successfully";
}


Thanks & Regards
Santosh

Friday, September 3, 2010

Validation Groups in ASP.NET 2.0

Validation groups is a new feature of asp.net 2.0.Validation groups help you to group the controls in a page and you can have separate submit buttons for each group.When you submit a group of values from a group,the validation controls pertaining to that group alone is executed.

Here is a example how to use validation group.
On clicking of Save Button,it should fire the Required Field validator of Name is required fields only. In the same way,on clicking Save Password it should fire
the Required Field validator only for Password is required fields.

For Group1
 <asp:TextBox ID="txtusername" runat="server" ValidationGroup="Group1"></asp:TextBox>  
<asp:RequiredFieldValidator ID="rfvUname" runat="server" ControlToValidate="txtusername"
ErrorMessage="Name is required." ValidationGroup="Group1">*</asp:RequiredFieldValidator>
<asp:Button ID="btnSave" runat="server" Text="Save" ValidationGroup="Group1" />


For Group2
 <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" ValidationGroup="Group2></asp:TextBox>  
<asp:RequiredFieldValidator ID="rfvpass" runat="server" ControlToValidate="txtPassword"
ErrorMessage="Password is required." ValidationGroup="Group2">*</asp:RequiredFieldValidator>
<asp:Button ID="btnSavePass" runat="server" Text="Save Password" ValidationGroup="Group2" />


Thanks & Regards
Santosh

Thursday, September 2, 2010

asp.net and c# interview Questions and Answers

1. What is a static class?
Ans.A static class is a class which can not be instantiated using the ‘new’ keyword. They also only contain static members,are sealed and have a private constructor.
Static classes are classes that contain only static members.A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword
to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example:
UtilityClass.MethodA();

A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. For example, in the .NET Framework Class Library, the static System.Math class contains methods that perform mathematical operations,without any requirement to store or retrieve data that is unique to a particular instance of the Math class. That is, you apply the members of the class by specifying the class name and the method name, as shown in the following example.
 public static class TemperatureConverter  
 {  
      public static double CelsiusToFahrenheit(string temperatureCelsius)  
      {  
           // Convert argument to double for calculations.  
           double celsius = Double.Parse(temperatureCelsius);  
           // Convert Celsius to Fahrenheit.  
           double fahrenheit = (celsius * 9 / 5) + 32;  
           return fahrenheit;  
      }  
      public static double FahrenheitToCelsius(string temperatureFahrenheit)  
      {  
           // Convert argument to double for calculations.  
           double fahrenheit = Double.Parse(temperatureFahrenheit);  
           // Convert Fahrenheit to Celsius.  
           double celsius = (fahrenheit - 32) * 5 / 9;  
           return celsius;  
      }  
 }  
 class TestTemperatureConverter  
 {  
      static void Main()  
      {  
           Console.WriteLine("Please select the convertor direction");  
           Console.WriteLine("1. From Celsius to Fahrenheit.");  
           Console.WriteLine("2. From Fahrenheit to Celsius.");  
           Console.Write(":");  
           string selection = Console.ReadLine();  
           double F, C = 0;  
           switch (selection)  
           {  
                case "1":  
                Console.Write("Please enter the Celsius temperature: ");  
                F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());  
                Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);  
                break;  
                case "2":  
                Console.Write("Please enter the Fahrenheit temperature: ");  
                C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine());  
                Console.WriteLine("Temperature in Celsius: {0:F2}", C);  
                break;  
                default:  
                Console.WriteLine("Please select a convertor.");  
                break;  
           }  
           // Keep the console window open in debug mode.  
           Console.WriteLine("Press any key to exit.");  
           Console.ReadKey();  
      }  
 }  

/* Example Output:
Please select the convertor direction
1. From Celsius to Fahrenheit.
2. From Fahrenheit to Celsius.
:2
Please enter the Fahrenheit temperature: 20
Temperature in Celsius: -6.67
Press any key to exit.
*/

The following list provides the main features of a static class:
- Contains only static members.
- Cannot be instantiated.
- Is sealed.
- Cannot contain Instance Constructors.
There are few limitations for static classes
- It can only contain static members (members explicitly marked with keyword ‘static’)
- It can not be instantiated
- It is sealed by default (i.e., it can not be inherited)
- It can not contain a constructor (although it may have a static constructor)

The static classes might be useful when we want a class which can not be instantiated or which should only be initiated once (Singleton class).
We may achieve the same functionality by declaring all members in ordinary class as static and making its constructor private. But when using
static classes, compiler ensures that none of the member of its members is non-static (i.e., all members are static).

2. What is static member?
Ans.A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.

It is more typical to declare a non-static class with some static members, than to declare an entire class as static. Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.

Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.

Although a field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that is used for static fields. No object instance is required.

C# does not support static local variables (variables that are declared in method scope).

You declare static class members by using the static keyword before the return type of the member, as shown in the following example:

public class Automobile
{
public static int NumberOfWheels = 4;
public static int SizeOfGasTank
{
get
{
return 15;
}
}
public static void Drive() { }
public static event EventType RunOutOfGas;

// Other non-static fields and properties...
}
Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member, as shown in the following example:
Automobile.Drive();
int i = Automobile.NumberOfWheels;

If your class contains static fields, provide a static constructor that initializes them when the class is loaded.

A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for a null object references. However, most of the time the performance difference between the two is not significant.

The C# provides a special type of constructor known as static constructor to initialize the static data members when the class is loaded at first. Remember
that, just like any other static member functions, static constructors can't access non-static data members directly.

The name of a static constructor must be the name of the class and even they don't have any return type. The keyword static is used to differentiate the
static constructor from the normal constructors. The static constructor can't take any arguments. That means there is only one form of static constructor,
without any arguments. In other way it is not possible to overload a static constructor.

We can't use any access modifiers along with a static constructor.

// C# static constructor
// Author: rajeshvs@msn.com
using System;
class MyClass
{
public static int x;
public static int y;
static MyClass ()
{
x = 100;
Y = 200;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y);
}
}


Note that static constructor is called when the class is loaded at the first time. However we can't predict the exact time and order of static constructor
execution. They are called before an instance of the class is created, before a static member is called and before the static constructor of the derived class
is called.

3. What is static function?

Ans.A static function is another term for a static method. It allows you to execute the function without creating an instance of its defining class.
They are similar to global functions. An example of a static function could be: ConvertFromFarenheitToCelsius with a signature as follows:

public static double ConvertFromFarenheitToCelsius (string valToConvert)
{
//add code here
}
Inside a C# class, member functions can also be declared as static. But a static member function can access only other static members. They can access non-static
members only through an instance of the class.

We can invoke a static member only through the name of the class. In C#, static members can't invoked through an object of the class as like in C++ or JAVA.
// C#:static & non-static
// Author: rajeshvs@msn.com
using System;
class MyClass
{
private static int x = 20;
private static int y = 40;
public static void Method()
{
Console.WriteLine("{0},{1}",x,y);
}
}
class MyClient
{
public static void Main()
{
MyClass.Method();
}
}

4. What is static constructor?
Ans.A static constructor has a similar function as a normal constructor i.e. it is automatically called the first time a class is loaded. The differences between
a conventional constructor are that it cannot be overloaded, cannot have any parameters nor have any access modifiers and must be preceded by the
keyword static. In addition, a class with a static constructor may only have static members.

5. How can we inherit a static variable?
6. How can we inherit a static member?
Ans. of 5 & 6
When inheriting static members there is no need to instantiate the defining class using the ‘new’ keyword.

 public class MyBaseClass  
 {  
      MyBaseClass()  
      {  
      }  
      public static void PrintName()  
      {  
      }  
 }  
 public class MyDerivedClass : MyBaseClass  
 {  
      MyDerivedClass ()  
      {  
        public void DoSomething()  
           {  
                MyBaseClass.GetName();  
           }  
      }  
 }  
7. Can we use a static function with a non-static variable?
Ans.No.
8. How can we access static variable?
Ans.
By employing the use of a static member field as follows:
 public class CashSales  
 {  
      //declare static member field  
      private static int maxUnitsAllowed = 50;  
      //declare method to return maximum number of units allowed  
      public static int GetMaxUnitsAllowed ()  
      {  
           Return maxUnitsAllowed;  
      }  
 }  
The static field can now be accessed by simply doing CashSales.GetMaxUnitsAllowed(). No need to create an instance of the class.

9. Why main function is static?
Ans.Because it is automatically loaded by the CLR and initialised by the runtime when the class is first loaded. If it wasn’t static an instance of
the class would first need to be created and initialised.

10. How will you load dynamic assembly? How will create assesblies at run time?
Ans.
Load assembly:
By using classes from the System.Reflection namespace.
Assembly x = Assembly.LoadFrom( “LoadMe.dll” );

Create assembly;
Use classes from System.CodeDom.Compiler;

11. What is Reflection?
Ans.The System.Reflection namespace provides us with a series of classes that allow us to interrogate the codebase at run-time and perform functions
such as dynamically load assemblies, return property info e.t.c.

12. If I have more than one version of one assemblies, then how will I use old version (how/where to specify version number?) in my application?
Ans.The version number is stored in the following format: …. The assembly manifest can then contain a reference to which version number we want to use.

13. How do you create threading in.NET? What is the namespace for that?
Ans.
System.Threading;

//create new thread using the thread class’s constructor

Thread myThread = new Thread(new ThreadStart (someFunction));

14. What do you mean by Serialize and MarshalByRef?
Ans.
Serialization is the act of saving the state of an object so that it can be recreated (i.e deserialized) at a later date.
The MarshalByRef class is part of the System.Runtime.Remoting namespace and enables us to access and use objects that reside in different application
domains. It is the base class for objects that need to communicate across application domains. MarshalByRef objects are accessed directly within their own
application domain by using a proxy to communicate. With MarshalByValue the a copy of the entire object is passed across the application domain

15. What is the difference between Array and LinkedList?
Ans.An array is a collection of the same type. The size of the array is fixed in its declaration.
A linked list is similar to an array but it doesn’t have a limited size.

16. What is Asynchronous call and how it can be implemented using delegates?
Ans.
A synchronous call will wait for a method to complete before program flow is resumed. With an asynchronous call the program flow continues whilst the method executes.

//create object
SomeFunction objFunc = new SomeFunction();

//create delegate
SomeDelegate objDel = new SomeDelegate(objFunc.FunctionA);

//invoke the method asynchronously (use interface IAsyncResult)
IAsyncResult asynchCall = SomeDelegate.Invoke();

17. How to create events for a control? What is custom events? How to create it?
Ans.
An event is a mechanism used in a class that can be used to provide a notification when something interesting happens. (typical evens in a windows application
include: change text in textbox, double click or click a button, select an item in dropdown box).
A custom event is an event created by the user that other developers can use. For example assuming that we have a CashTransaction class and we have a bank
balance property in that class. We may want to set-up an event that provides a notification when the bank balance drops below a certain amount. In order to
produce an event the process would be roughly as follows:
Create the class for the event derived from EventArgs.
Create a delegate with a return type of void.
Create a class containing the method that will activate the event.
Create a class with methods to handle the event.

18. If you want to write your own dot net language, what steps you will you take care?
Ans.We will need to ensure that the high level code is compiled to MSIL (Microsoft intermediate language) so that it can be interpreted by the CLR.

19. Describe the diffeerence between inline and code behind - which is best in a loosely coupled solution?
Ans.
The term ‘code behind’ refers to application code that is not embedded within the ASPX page and is separated out into a separate file which is then referenced
from the ASPX page. Inline code is the traditional ASP architectural model where business logic code was embedded within the ASP page. Separating the business
logic code from the presentation layer offers several advantages:
1) It allows graphic designers and web developers to work on the presentation layer whilst the application developers concentrate on the business logic.
2) The codebehind file is compiled as a single dll increasing the efficiency of the application,
3) The codebehind model offers a true OO development platform,
4) It speeds up development time as it allows developers to fully maximise the features of the .NET framework such as Cahing, ViewState, Session, Smart Navigation etc.
5) Code is much easier to maintain and susceptible for change.
6) The compiler and VS.NET provides much better support for error checking, intellisense and debugging when using the code behind model.

20. How dot net compiled code will become platform independent?
Ans.
The raison d’etre for .NET was to cater for multiples languages on a single windows platform whereas the aim of Java was to be a single language on multiple
platforms. The only way that .NET can be platform independent is if there is a version of the .NET framework installed on the target machine.

21. Without modifying source code if we compile again, will it be generated MSIL again?
Ans.No.

22. How does you handle this COM components developed in other programming languages in.NET?
Ans.
use TlbImp.exe to import the COM types into your .NET project. If no type library for the COM component then use System.Runtime.InteropServices
use RegAsm.exe to call a .NET developed component in a COM application.

23. How CCW (Com Callable Wrapper) and RCW (Runtime Callable Wrappers) works?
Ans.
CCW: When a COM application calls a NET object the CLR creates the CCW as a proxy since the COM application is unable to directly access the .NET object.
RCW: When a .NET application calls a COM object the CLR creates the RCW as a proxy since the .NET application is unable to directly access the .COM object.

24. What are the new thee features of COM+ services, which are not there in COM (MTS)?
Ans.
Role based security.
Neutral apartment threading.
New environment called context which defines the execution environment

25. What are the differences between COM architecture and.NET architecture?
Ans.
.Net architecture has superseded the old COM architecture providing a flexible rapid application development environment which can be used to create windows,
web and console applications and web services. .NET provides a powerful development environment that can be used to create objects in any .NET compliant language.
.NET addresses the previous problems of dll hell with COM by providing strongly named assemblies and side-by-side execution where two assemblies with the same name can run on the same box.

26. Can we copy a COM dll to GAC folder?
Ans.
No. It only stores .NET assemblies.

27. What is Shared and Repeatable Inheritance?
Ans.


28. Can you explain what inheritance is and an example of when you might use it?
Ans.
Inheritance is a fundamental feature of any OO language. It allows us to inherit the members and attributes from a base class to a new derived class. This
leads to increased code reusability and also makes applications easier to develop, maintain and extend as the new derived class can contain new features not
available in the base class whilst at the same time preserving the attributes inherited from the base class.

29. How can you write a class to restrict that only one object of this class can be created (Singleton class)?
Ans.
Use the singleton design pattern.
 public sealed class Singleton  
 {  
   static readonly Singleton Instance=new Singleton();  
      static Singleton()  
      {  
      }  
      Singleton()  
      {  
      }  
      public static Singleton Instance  
      {  
           get  
           {  
                return Instance;  
           }  
      }  
 }  
30. What are virtual destructures?
Ans.
A constructor can not be virtual but a destructor may. Use virtual destructors when you want to implement polymorphic tearing down of an object.

31. What is close method? How its different from Finalize and Dispose?
Ans.
finalise is the process that allows the garbage collector to clean up any unmanaged resources before it is destroyed.
The finalise method can not be called directly; it is automatically called by the CLR. In order to allow more control over the release of unmanaged resources
the .NET framework provides a dispose method which unlike finalise can be called directly by code.
Close method is same as dispose. It was added as a convenience.

32. What is Boxing and UnBoxing?
Ans.
Boxing is the process of converting a value type to a reference type. More specifically it involves encapsulating a copy of the object and moving it from
stack to heap. Unboxing is the reverse process.

33. What is check/uncheck?
Ans.
checked: used to enable overflow checking for arithmetic and conversion functions.
unchecked: used to disable overflow checking for arithmetic and conversion functions

34. What is the use of base keyword? Tell me a practical example for base keyword’s usage?
Ans.
The base keyword is used to access members of the base class from within a derived class:
* Call a method on the base class that has been overridden by another method.
* Specify which base-class constructor should be called when creating instances of the derived class.

A base class access is permitted only in a constructor, an instance method, or an instance property accessor.
It is an error to use the base keyword from within a static method.
Example:In this example, both the base class, Person, and the derived class, Employee, have a method named Getinfo. By using the base keyword,
it is possible to call the Getinfo method on the base class, from within the derived class.
// keywords_base.cs
// Accessing base class members
 using System;  
 public class Person  
 {  
 protected string ssn = "444-55-6666";  
 protected string name = "John L. Malgraine";  
 public virtual void GetInfo()  
 {  
 Console.WriteLine("Name: {0}", name);  
 Console.WriteLine("SSN: {0}", ssn);  
 }  
 }  
 class Employee: Person  
 {  
 public string id = "ABC567EFG";  
 public override void GetInfo()  
 {  
 // Calling the base class GetInfo method:  
 base.GetInfo();  
 Console.WriteLine("Employee ID: {0}", id);  
 }  
 }  
 class TestClass {  
 public static void Main()  
 {  
 Employee E = new Employee();  
 E.GetInfo();  
 }  
 }  
35. What are the different.NET tools which you used in projects?
Ans:Just read your question once again and thought Interviewer might be asking about the development tool you have used to develop ASP.NET projects.
So your answer can be Visual Studio 2005 or 2008 or 2010 whatever you have used, you may also tell Visual Web Developer or any other tool you might
have used to develop your ASP.NET Projects

Remaining answers coming soon
36. What happens when you try to update data in a dataset in.NET while the record is already deleted in SQL Server as backend?
37. What is concurrency? How will you avoid concurrency when dealing with dataset?
38. How do you merge two datasets into the third dataset in a simple manner?
39. If you are executing these statements in commandObject.Select * from Table1; Select * from Table2? How you will deal result set?
40. How do you sort a dataset.
 DataSet dt=new DataSet("mydata");  
 mydata.Fill(dt,"mydata");  
 DataView myDataView = dt.Tables["mydata"].DefaultView ;  
 myDataView.Sort = "id DESC";  
 DataGrid1.DataSource=myDataView;  
 DataGrid1.DataBind();  


Thanks & Regards
Santosh

Wednesday, September 1, 2010

How to add comma in a int or decimal value

This code show how to add comma into int or decimal value.Suppose we have a value 33000
and want to display this 33,000.00.

string FirstP = "";
string SecP = "";
string Finalstr = "";
int MyValue = Convert.ToInt32(Projected);
string myStr = MyValue.ToString();
int Length = myStr.Length;
string dc = ".00";

do
{
FirstP = myStr.Substring(0, Length - 3);
SecP = myStr.Substring(Length - 3, 3);
Finalstr = "," + SecP + Finalstr;
myStr = FirstP;
Length = myStr.Length;
}
while (Length > 3);

if (myStr == "")
{
Finalstr = Finalstr.Substring(1, Finalstr.Length);
}
else
{
Finalstr = myStr + Finalstr + dc;
}

lblSalary.Text = Finalstr.ToString();

ASP.NET Validation Controls with example

 Learning Technique for freshers : R3C2  
   
 1.RequiredFieldValidation Control  
 2.RangeValidator Control  
 3.RegularExpressionValidator Control  
 4.CompareValidator Control  
 5.CustomValidator Control  
   
 Properties of Validation Controls.  
   
 ControlToValidate - Id of control Which you want to validate.  
 ErrorMessage - Message that will be displayed in the validation summary.  
 IsValid - Whether or not the control is valid.  
 Validate - Method to validate the input control and update the IsValid property.  
 Display - How the error message will display.options are given below  
 None:Message is never displayed.  
 Static:Validation message will display in the page layout.  
 Dynamic:Validation message is dynamically added to the page if validation fails.  
   
 Example with code:  
   
 1.RequiredFieldValidation:It is simple validation control which checks data is entered or not.  
 <asp:textbox id="txtEmpName" runat="server"/>  
 <asp:RequiredFieldValidator id="rfvtxtbox" runat="server" ControlToValidate="txtEmpName"  
 ErrorMessage="* Please enter the employee name" Display="dynamic">*  
 </asp:RequiredFieldValidator>  
   
 2.RangeValidator:It checks to see if a control value is within a valid range or not.  
 <asp:textbox id="txtDOB" runat="server"/>  
 <asp:RangeValidator id="rangeVal" runat="server"  
 ControlToValidate="txtDOB1"  
 MaximumValue="12/06/2009"  
 MinimumValue="01/01/1983"  
 Type="Date"  
 ErrorMessage="* Please enter the valid date" Display="static">*</asp:RangeValidator>  
   
 3.RegularExpressionValidator:It can be used for email validation or any specified string based on pattern matching.  
 E-mail: <asp:textbox id="txtEmail" runat="server"/>  
 <asp:RegularExpressionValidator id="revemail" runat="server"  
 ControlToValidate="txtEmail"  
 ValidationExpression=".*@.*\..*"  
 ErrorMessage="* Please enter valid e-mail ."  
 display="dynamic">*  
 </asp:RegularExpressionValidator>  
   
 4.CompareValidator: It allows you to make comparisons between two form controls and also compare values contained with  
 these controls to constants that specified by userd.  
   
 New Password: <asp:textbox id="txtNewPass" runat="server"/><br />  
 Confirm Passowrd: <asp:textbox id="txtConfirmPass" runat="server"/><br />  
 <asp:CompareValidator id="valCompare" runat="server"  
 ControlToValidate="txtNewPass" ControlToCompare="txtConfirmPass"  
 Operator="Equals"  
 ErrorMessage="* New Password and confirm password are not same"  
 Display="dynamic">*  
 </asp:CompareValidator>  
   
 5.CustomValidator:It allows you to write your own server-side or client-side validations logic and it can be easily applied to your web forms controls.  
 <asp:CustomValidator ID="cv" runat="server"   
 ControlToValidate="txtName" ClientValidationFunction="customvalidationr"   
 ErrorMessage="Please enter correct name"></asp:CustomValidator>  
 <asp:TextBox ID="txtName" runat="server"></asp:TextBox>  
 <asp:Button ID="btnSubmit" runat="server" />  
   
 Client side javascript  
   
 <script type="text/javascript">  
 function customvalidation(oSrc,args)  
 {   
   
 write your code here  
 }  
 </script>