Archive

Author Archive

How to implement CAPTCHA image validation in ASP.Net/C# OR CAPTCHA image validator Sample in ASP.Net/C#


                                   DOWNLOAD SOURCE CODE FOR CAPTCHA IMAGE VALIDATION IN ASP.NET

What is CAPTCHA and why we are using CAPTCHA

A CAPTCHA  is a type of challenge-response test used in computing as an attempt to ensure that the response is generated by a human being. The process usually involves a computer asking a user to complete a simple test which the computer is able to grade. These tests are designed to be easy for a computer to generate but difficult for a computer to solve, but again easy for a human. If a correct solution is received, it can be presumed to have been entered by a human. A common type of CAPTCHA requires the user to type letters and/or digits from a distorted image that appears on the screen. Such tests are commonly used to prevent unwanted internet bots from accessing websites, since a normal human can easily read a CAPTCHA, while the bot cannot process the image letters and therefore, cannot answer properly, or at all.

How to implement CAPTCHA validation/CAPTCHA verification in ASP.Net/C#

CAPTCHA image can be generated using ASP.Net codes and we can validate the code that user enter with the code in the CAPTCHA image. Here we are going to do a sample application that demonstrates how to create a CAPTCHA image using C# codes and how we can validate the user inputs with the CPATCH code. We are having two aspx pages and one class .cs file in the sample application.

A very simple application sample for CPTCHA validation

In the page load, first of all we are creating a 6 digit random number and stored in the session. By using this random number we creates a image suing System.Drawing package by giving some width,height,font family and alignment of the numbers, So the user can able to view the codes in the CAPTCHA image but it is difficult to read using system.

DOWNLOAD SOURCE CODE FOR CAPTCHA IMAGE VALIDATION IN ASP.NET

Below is the Class that we used for creating a CAPTCHA image with random number

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;

namespace CaptchaImage
{
       /// <summary>
       /// Summary description for CaptchaImage.
       /// </summary>
       public class CaptchaImage
       {
              // Public properties (all read-only).
              public string Text
              {
                     get { return this.text; }
              }
              public Bitmap Image
              {
                     get { return this.image; }
              }
              public int Width
              {
                     get { return this.width; }
              }
              public int Height
              {
                     get { return this.height; }
              }

              // Internal properties.
              private string text;
              private int width;
              private int height;
              private string familyName;
              private Bitmap image;

              // For generating random numbers.
              private Random random = new Random();

              // ====================================================================
              // Initializes a new instance of the CaptchaImage class using the
              // specified text, width and height.
              // ====================================================================
              public CaptchaImage(string s, int width, int height)
              {
                     this.text = s;
                     this.SetDimensions(width, height);
                     this.GenerateImage();
              }

              // ====================================================================
              // Initializes a new instance of the CaptchaImage class using the
              // specified text, width, height and font family.
              // ====================================================================
              public CaptchaImage(string s, int width, int height, string familyName)
              {
                     this.text = s;
                     this.SetDimensions(width, height);
                     this.SetFamilyName(familyName);
                     this.GenerateImage();
              }

              // ====================================================================
              // This member overrides Object.Finalize.
              // ====================================================================
              ~CaptchaImage()
              {
                     Dispose(false);
              }

              // ====================================================================
              // Releases all resources used by this object.
              // ====================================================================
              public void Dispose()
              {
                     GC.SuppressFinalize(this);
                     this.Dispose(true);
              }

              // ====================================================================
              // Custom Dispose method to clean up unmanaged resources.
              // ====================================================================
              protected virtual void Dispose(bool disposing)
              {
                     if (disposing)
                           // Dispose of the bitmap.
                           this.image.Dispose();
              }

              // ====================================================================
              // Sets the image width and height.
              // ====================================================================
              private void SetDimensions(int width, int height)
              {
                     // Check the width and height.
                     if (width <= 0)
                           throw new ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero.");
                     if (height <= 0)
                           throw new ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.");
                     this.width = width;
                     this.height = height;
              }

              // ====================================================================
              // Sets the font used for the image text.
              // ====================================================================
              private void SetFamilyName(string familyName)
              {
                     // If the named font is not installed, default to a system font.
                     try
                     {
                           Font font = new Font(this.familyName, 12F);
                           this.familyName = familyName;
                           font.Dispose();
                     }
                     catch (Exception ex)
                     {
                           this.familyName = System.Drawing.FontFamily.GenericSerif.Name;
                     }
              }

              // ====================================================================
              // Creates the bitmap image.
              // ====================================================================
              private void GenerateImage()
              {
                     // Create a new 32-bit bitmap image.
                     Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);

                     // Create a graphics object for drawing.
                     Graphics g = Graphics.FromImage(bitmap);
                     g.SmoothingMode = SmoothingMode.AntiAlias;
                     Rectangle rect = new Rectangle(0, 0, this.width, this.height);

                     // Fill in the background.
                     HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White);
                     g.FillRectangle(hatchBrush, rect);

                     // Set up the text font.
                     SizeF size;
                     float fontSize = rect.Height + 1;
                     Font font;
                     // Adjust the font size until the text fits within the image.
                     do
                     {
                           fontSize--;
                           font = new Font(this.familyName, fontSize, FontStyle.Bold);
                           size = g.MeasureString(this.text, font);
                     } while (size.Width > rect.Width);

                     // Set up the text format.
                     StringFormat format = new StringFormat();
                     format.Alignment = StringAlignment.Center;
                     format.LineAlignment = StringAlignment.Center;

                     // Create a path using the text and warp it randomly.
                     GraphicsPath path = new GraphicsPath();
                     path.AddString(this.text, font.FontFamily, (int) font.Style, font.Size, rect, format);
                     float v = 4F;
                     PointF[] points =
                     {
                           new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
                           new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
                            new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v),
                           new PointF(rect.Width - this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v)
                     };
                     Matrix matrix = new Matrix();
                     matrix.Translate(0F, 0F);
                     path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);

                     // Draw the text.
                     hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray);
                     g.FillPath(hatchBrush, path);

                     // Add some random noise.
                     int m = Math.Max(rect.Width, rect.Height);
                     for (int i = 0; i < (int) (rect.Width * rect.Height / 30F); i++)
                     {
                           int x = this.random.Next(rect.Width);
                           int y = this.random.Next(rect.Height);
                           int w = this.random.Next(m / 50);
                           int h = this.random.Next(m / 50);
                           g.FillEllipse(hatchBrush, x, y, w, h);
                     }

                     // Clean up.
                     font.Dispose();
                     hatchBrush.Dispose();
                     g.Dispose();

                     // Set the image.
                     this.image = bitmap;
              }
       }
}

DOWNLOAD SOURCE CODE FOR CAPTCHA IMAGE VALIDATION IN ASP.NET

About these ads

How to implement SQL Bulk Copy in SQL Server OR Bulk insert into SQL Server using SQL BulkCopy

October 17, 2012 1 comment

SqlBulkCopy for insert multiple rows of data into table in SQL Server

Sometimes we need to insert bulk amount of data into a table in SQL. We can insert bulk data to SQL in different methods. Here we are going to demonstrate how to insert large amount of data using SQL Bulk Copy method.

Example of SQL BulkCopy method

Here we are going to insert multiple rows of sample data into Employee table. First of all create a table in SQL named Employee. After that  create sample data for employee table and finally this multiple rows of employee data insert into table using SQL bulk copy method.

Create a Table in SQL 

CREATE TABLE Employee
(
ID INT,
EmpName varchar(200),
Department varchar(200),
DOB DateTime
);

SQLMulkCopy Example in SQL Server

SQLMulkCopy Example in SQL Server

C# Code to generate sample data and insertion using SQL Bulk Copy

private void loadDataBySQLBulkCopy()
        {
            DataTable dtTblEmployee = new DataTable();
            dtTblEmployee.Columns.Add("ID", typeof(Int32));
            dtTblEmployee.Columns.Add("EmpName", typeof(String));
            dtTblEmployee.Columns.Add("Department", typeof(String));
            dtTblEmployee.Columns.Add("DOB", typeof(DateTime));

            DataRow dtrow = dtTblEmployee.NewRow(); // Create New Row
            dtrow["ID"] = 1; //Bind Data to Columns
            dtrow["EmpName"] = "Wazeem";
            dtrow["Department"] = "Admin";
            dtrow["DOB"] = "1990-10-16 12:00:00.000";
            dtTblEmployee.Rows.Add(dtrow);

            dtrow = dtTblEmployee.NewRow(); // Create New Row
            dtrow["ID"] = 2; //Bind Data to Columns
            dtrow["EmpName"] = "Aslam";
            dtrow["Department"] = "HR";
            dtrow["DOB"] = "1987-05-16 12:00:00.000";
            dtTblEmployee.Rows.Add(dtrow);

            dtrow = dtTblEmployee.NewRow(); // Create New Row
            dtrow["ID"] = 3; //Bind Data to Columns
            dtrow["EmpName"] = "John";
            dtrow["Department"] = "Finance";
            dtrow["DOB"] = "1992-12-11 12:00:00.000";
            dtTblEmployee.Rows.Add(dtrow);

            dtrow = dtTblEmployee.NewRow(); // Create New Row
            dtrow["ID"] = 4; //Bind Data to Columns
            dtrow["EmpName"] = "Mishal";
            dtrow["Department"] = "Infra structure";
            dtrow["DOB"] = "1989-04-01 12:00:00.000";
            dtTblEmployee.Rows.Add(dtrow);

            SqlBulkCopy bulkCopy = new SqlBulkCopy(
                "server=TEST;database=TEST;uid=test;password=test",
                SqlBulkCopyOptions.TableLock);
            bulkCopy.DestinationTableName = "dbo.Employee";
            bulkCopy.WriteToServer(dtTblEmployee);

        }

How to merge two data tables in ASP.Net/C# OR Merge 2 DataTables and store in a new one in ASP.Net/C#

October 14, 2012 Leave a comment

Merge multiple data-tables data into a another data-table using C#/ASP.Net

Here we are going to demonstrate a sample application which shows merge two data tables  in ASP.Net. In this sample we are having two data tables with some data and merge data of each tables data. We binds first data table to a data grid second one to another grid and third data grid binds with merged data table.

Merge data tables in C#/ASP.Net

Merge data tables in C#/ASP.Net

 

ASPX Page for Example of merge two datatables in C#/ASP.Net

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MergeDataTable.aspx.cs"
 Inherits="ExperimentLab.MergeDataTable" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 First DataTable
 <asp:GridView ID="gdDataTableOne" runat="server" /><br />
 Second DataTable
 <asp:GridView ID="gdDataTableTwo" runat="server" /><br />
 Merged DattaTable
 <asp:GridView ID="gdDataTableMergedData" runat="server" /><br />
 </div>
 </form>
</body>
</html>
-*******

CODE BEHIND Page for Merge datatable in C#/ASP.Net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace ExperimentLab
{
 public partial class MergeDataTable : System.Web.UI.Page
 {
 DataTable dtOne = new DataTable();
 DataTable dtTwo = new DataTable();
protected void Page_Load(object sender, EventArgs e)
 {
 fillDataTableOne();
 fillDataTableTwo();
 mergeDataTables();
 }
private void mergeDataTables()
 {
 dtOne.Merge(dtTwo, false);
 gdDataTableMergedData.DataSource = dtOne;
 gdDataTableMergedData.DataBind();
 }
private void fillDataTableOne()
 { 
 dtOne.Columns.Add("EmpID", typeof(Int32));
 dtOne.Columns.Add("EmployeeName", typeof(string));
 dtOne.Columns.Add("Department", typeof(string));
 dtOne.Columns.Add("City", typeof(string));
DataRow dtOnerow = dtOne.NewRow(); // Create New Row
 dtOnerow["EmpID"] = 1; //Bind Data to Columns
 dtOnerow["EmployeeName"] = "Ram";
 dtOnerow["Department"] = "Admin";
 dtOnerow["City"] = "Kochi";
 dtOne.Rows.Add(dtOnerow);
dtOnerow = dtOne.NewRow(); // Create New Row
 dtOnerow["EmpID"] = 2; //Bind Data to Columns
 dtOnerow["EmployeeName"] = "Mahesh";
 dtOnerow["Department"] = "Finance";
 dtOnerow["City"] = "Delhi";
 dtOne.Rows.Add(dtOnerow);
dtOnerow = dtOne.NewRow(); // Create New Row
 dtOnerow["EmpID"] = 3; //Bind Data to Columns
 dtOnerow["EmployeeName"] = "Raj";
 dtOnerow["Department"] = "Admin";
 dtOnerow["City"] = "Kolkata";
 dtOne.Rows.Add(dtOnerow);
dtOnerow = dtOne.NewRow(); // Create New Row
 dtOnerow["EmpID"] = 4; //Bind Data to Columns
 dtOnerow["EmployeeName"] = "Virbal";
 dtOnerow["Department"] = "HR";
 dtOnerow["City"] = "Mumbai";
 dtOne.Rows.Add(dtOnerow);
gdDataTableOne.DataSource = dtOne;
 gdDataTableOne.DataBind();
 }
private void fillDataTableTwo()
 {
dtTwo.Columns.Add("EmpID", typeof(Int32));
 dtTwo.Columns.Add("EmployeeName", typeof(string));
 dtTwo.Columns.Add("Department", typeof(string));
 dtTwo.Columns.Add("City", typeof(string));
DataRow dtTworow = dtTwo.NewRow(); // Create New Row
 dtTworow["EmpID"] = 5; //Bind Data to Columns
 dtTworow["EmployeeName"] = "John";
 dtTworow["Department"] = "Delivery";
 dtTworow["City"] = "Goa";
 dtTwo.Rows.Add(dtTworow);
dtTworow = dtTwo.NewRow(); // Create New Row
 dtTworow["EmpID"] = 6; //Bind Data to Columns
 dtTworow["EmployeeName"] = "Jacob";
 dtTworow["Department"] = "Finance";
 dtTworow["City"] = "Kolkata";
 dtTwo.Rows.Add(dtTworow);
dtTworow = dtTwo.NewRow(); // Create New Row
 dtTworow["EmpID"] = 7; //Bind Data to Columns
 dtTworow["EmployeeName"] = "Srini";
 dtTworow["Department"] = "HR";
 dtTworow["City"] = "Jaipur";
 dtTwo.Rows.Add(dtTworow);
dtTworow = dtTwo.NewRow(); // Create New Row
 dtTworow["EmpID"] = 8; //Bind Data to Columns
 dtTworow["EmployeeName"] = "Gopal";
 dtTworow["Department"] = "InfraStructure";
 dtTworow["City"] = "Chennai";
 dtTwo.Rows.Add(dtTworow);
gdDataTableTwo.DataSource = dtTwo;
 gdDataTableTwo.DataBind();
 }
 
 }
}




How to implement Password validation in ASP.Net/C# OR Implement Password strength using Jquery in ASP.Net

October 10, 2012 1 comment

 

DOWNLOAD SOURCE CODE FOR PASSWORD STRENGTH CHECKER

How to show Password Strength image to user in ASP.Net

Register/change password pages on most of the application showing password strength information to user while entering password in the textbox. It allows to user to enter a strong password for register the pages. We can implement Password Strength Checker in different methods in ASP.Net application. Its better to do it in the client side itself so that user doesn’t feels post back in the page.

Implement Password Strength Checker using Jquery

Here we are going to demonstrate a sample application to implement Password Strength Checker using Jquery. The application shows the status of entered password by each alphabet changes in the textbox such as Week, Good, Strong etc..

Password_Strength_Checker

ASPX/HTML Page for Password Strength Checker  

<!DOCTYPE html>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title>jQuery Validation Plugin Password Extension demo</title>
 <link rel="stylesheet" type="text/css" media="screen" href="../jquery.validate.password.css" />
 <script type="text/javascript" src="../lib/jquery.js"></script>
 <script type="text/javascript" src="../lib/jquery.validate.js"></script>
 <script type="text/javascript" src="../jquery.validate.password.js"></script>
 <script id="demo" type="text/javascript">
 $(document).ready(function () {
 $("#register").validate();
 $("#password").valid();
});
</script>
 <style>
 label, input
 {
 float: left;
 }
 input
 {
 margin-left: 1em;
 }
 label.error
 {
 display: none !important;
 }
 .password-meter
 {
 float: left;
 }
 </style>
</head>
<body>
 <form id="register">
 <div>
 Password Strength Checker Demo Using JQuery.. 
powered by <a href="http://tuvian.con">
 tuvian</a>
 </div>
 <br />
 <br />
 <label for="password">
 Password:</label>
 <input class="password" name="password" id="password" />
 <div class="password-meter">
 <div class="password-meter-message">
 &nbsp;</div>
 <div class="password-meter-bg">
 <div class="password-meter-bar">
 </div>
 </div>
 </div>
 </form>
</body>
</html>

 

DOWNLOAD SOURCE CODE FOR PASSWORD STRENGTH CHECKER

 

How to create breadcrumbs in ASP.Net/C# OR Show Navigations for each pages in ASP.Net/C# OR How to implement Sitemap in ASP.Net

October 2, 2012 2 comments

DOWNLOAD SOURCE CODE FOR BREADCRUMB EXAMPLE IN ASP.NET

What is breadcrumbs and what is the use of it?

Breadcrumbs typically appear horizontally across the top of a web page, often below title bars or headers. They provide links back to each previous page the user navigated through to get to the current page or-in hierarchical site structures-the parent pages of the current one. Breadcrumbs provide a trail for the user to follow back to the starting or entry point. A greater-than sign (>) often serves as hierarchy separator, although designers may use other glyphs <http://en.wikipedia.org/wiki/Glyph>  (such as » or >), as well as various graphical treatments.

Typical breadcrumbs look like this:

 Home page > Section page > Subsection page

How to implement breadcrumbs in ASP.Net/C# pages

In order to implement breadcrumbs in ASPX pages, we can use new pages called sitemaps. In ASP.NET the menu can be stored in a file to make it easier to maintain. This file is normally calledweb.sitemap, and is stored in the root directory of the web.

DOWNLOAD SOURCE CODE FOR BREADCRUMB EXAMPLE IN ASP.NET

BREADCRUMB EXAMPLE IN ASP.NET

Example for implementing sitemaps in ASP.Net/C# pages

We are going to demonstrate sample ASP.Net application for implementing Breadcrumbs in ASPX pages. First of all create a new ASP.Net project and create three pages home.aspx, aboutus.aspx  and contactus.aspx.  Then create a sitemap file by “Add New item > SiteMap” and mention the hierarchy of the pages in the sitemaps as follows

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >

  <siteMapNode url="Default.aspx" title="Home"  description="Home Page">
    <siteMapNode url="ContactUs.aspx" title="Contact US" 
                 description="Contact US Page" />
    <siteMapNode url="About.aspx" title="About"  description="About " >
      <siteMapNode url="AboutCompany.aspx" title="About Company" 
                   description="About Our Company" />
      <siteMapNode url="AboutService.aspx" title="About Service" 
                   description="About Our Services" />
    </siteMapNode>
  </siteMapNode>
</siteMap>

Once we created sitemap and mentioned the hierarchy of the pages we need to map this sitemaps into all pages that we need to show navigation as follows.

<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
    <asp:SiteMapPath ID="SiteMap1" runat="server">
    </asp:SiteMapPath>

Sample Application of Navigation Menu/Bread Crumbs  

web.sitemap

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
  <siteMapNode url="Default.aspx" title="Home"  description="Home Page">
    <siteMapNode url="ContactUs.aspx" title="Contact US" 
                 description="Contact US Page" />
    <siteMapNode url="About.aspx" title="About"  description="About " >
      <siteMapNode url="AboutCompany.aspx" title="About Company" 
                   description="About Our Company" />
      <siteMapNode url="AboutService.aspx" title="About Service" 
                   description="About Our Services" />
    </siteMapNode>
  </siteMapNode>
</siteMap>

 About.aspx

<%@ Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="About.aspx.cs" Inherits="BreadCrumb.About" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
    <asp:SiteMapPath ID="SiteMap1" runat="server">
    </asp:SiteMapPath>
    <h2>
        Welcome TO About US Page
    </h2>
    <br />
    <a href="AboutCompany.aspx" runat="server">About Our Company</a>
    <br />
    <a id="A1" href="AboutService.aspx" runat="server">About Our Services</a>
</asp:Content>

Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="BreadCrumb._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:SiteMapPath ID="SiteMap1" runat="server">
    </asp:SiteMapPath>
    <h2>
        Welcome to HOME PAGE
    </h2> 
</asp:Content>

 

 

AboutCompany.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
    CodeBehind="AboutCompany.aspx.cs" Inherits="BreadCrumb.AboutCompany" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
    <asp:SiteMapPath ID="SiteMap1" runat="server">
    </asp:SiteMapPath>
    <h2>
        This is the Page showing about our Company
    </h2>
</asp:Content>

AboutService.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
    CodeBehind="AboutService.aspx.cs" Inherits="BreadCrumb.AboutService" %>
 <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
    <asp:SiteMapPath ID="SiteMap1" runat="server">
    </asp:SiteMapPath>
    <h2>
        This is the Page showing about our Service
    </h2>
</asp:Content>
-


            DOWNLOAD SOURCE CODE FOR BREADCRUMB EXAMPLE IN ASP.NET

How to create a drag able and resizable div in ASP.Net/C# OR How to make a div Dragable and Resizable using Jquery in ASP.Net/C#

September 27, 2012 1 comment

                                    DOWNLOAD SOURCE CODE FOR DAG ABLE AND RE-SIZABLE DIV  

Resize and drag a div in ASPX page/HTML Page

Here we are going to demonstrate making a div that can be drag and resize by users. We are achieving this drag and resize of div functionality using Jquery files. We already posted some article related with Jquery and Javascript. Here we are again demonstrating a detailed post regarding Draggable and Resizable div using Jquery files.

Drag able Re-sizable Div in HTML/ASPX Page

Drag able and Resizable Div using Jquery in HTML/ASPX Page

For implementing drag and resize Div, we need to download following jquery and css files and included in the ASPX/HTML page.

1. jquery.min.js          - Download from here 

2. jquery-ui.min.js    - Download from here 

3. jquery-ui.css          - Download from here 

After downloading above files we need to create a HTML/ASPX Page and include above files as mentioned below.

<script src="jquery.min.js" type="text/javascript"></script>
 <script src="jquery-ui.min.js" type="text/javascript"></script>
 <link rel="stylesheet" href="jquery-ui.css"
 type="text/css" media="all" />

HTML/ASPX Page for creating drag able and re sizable div

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>Untitled Page</title>
 <script src="jquery.min.js" type="text/javascript"></script>
 <script src="jquery-ui.min.js" type="text/javascript"></script>
 <link rel="stylesheet" href="jquery-ui.css"
 type="text/css" media="all" />
 <style type="text/css">
 #resizediv
 {
 width: 150px;
 height: 150px;
 padding: 0.5em;
 background: #EB5E00;
 color: #fff;
 }
 </style>
 <script type="text/javascript">
$(document).ready(function () {
$("#resizediv").resizable();
$("#resizediv").draggable();
});
</script>
</head>
<body>
 <form id="form1" runat="server">
 <div id="resizediv">
 Drag me ... or Resize me....<br />
 This is a Div that can be Drag and Resize by you.. .
 </div>
 </form>
</body>
</html>

------

                        DOWNLOAD SOURCE CODE FOR DAG ABLE AND RE-SIZABLE DIV  

How to implement BalloonPopupExtender in ASP.Net/C# OR Ballon Popup Extender Sample in ASP.Net/C#

September 25, 2012 Leave a comment

                     DOWNLOAD SOURCE CODE FOR BALLOON POPUP EXTENDER EXAMPLE

How to display good POPUP Window in ASP.Net using Ajax?

Most of the ASP.Net application requires showing some POPUP window to user for showing some messages or information. Also in order to create a ToolTips in ASP.Net/C# web application it’s very difficult to achieve for good looking ToolTip. In the newest Ajax Control Toolkit includes an awesome good looking and more functional popup extender called Balloon POPUP Extender. It’s a very light weight and having good look and feel popup, also we can apply custom styles for POPUP. Balloon POPUP Extender can use as ToolTips in ASP.Net application.

Download and Register New AjaxControl Toolkit

For implementing Balloon POPUP Extender in ASP.Net/C# application, we need to download newest Ajax Control Toolkit and register to the Project references. You can download new Ajax Control Toolkit from this link. Right click the ‘References’ under the ASP.Net project from Visual Studio and browse the dll and press OK.

In the ASPX page we need to register this ajax toolkit dll like below mentioned code.

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

How to implement Balloon POPUP Extender in ASP.Net/C# Application?

After adding and register the Ajax Control Toolkit as mentioned above, we can start to implement the Balloon POPUP Extender. We can implement Balloon POPUP Extender while clicking/on mouse over/on focus of any server controls in ASP.Net. Below mentioned is the codes for implementing the same.

<ajax:BalloonPopupExtender ID="PopupControlExtender2" runat="server" 
TargetControlID="txtUserName"
 BalloonPopupControlID="pnlBalloon" Position="BottomRight" 
BalloonStyle="Cloud"
 BalloonSize="Medium" UseShadow="true" ScrollBars="Auto" 
DisplayOnMouseOver="true"
 DisplayOnFocus="false" DisplayOnClick="true" />

Balloon Popup Extender Sample

Balloon Popup Extender Sample

Balloon Popup Extender Sample


There are some properties are available for Balloon POPUP Extender control and we can adjust the size,color,style and controls of POPUP using these properties. Below are the main properties of Balloon POPUP Extender

TargetControlID – The ID of the control to attach to.

BalloonPopupControlID – The ID of the control to display.

Position – Optional setting specifying where the popup should be positioned relative to the target control. (TopRight, TopLeft, BottomRight, BottomLeft, Auto) Default value is Auto.

OffsetX/OffsetY – The number of pixels to offset the Popup from its default position, as specified by Position. Default value is 0.

BalloonStyle – Optional setting specifying the theme of balloon popup. (Cloud, Rectangle, Custom). Default value is Rectangle.

BalloonSize – Optional setting specifying the size of balloon popup. (Small, Medium and Large). Default value is Small.

CustomCssUrl – This is required if user choose BalloonStyle to Custom. This specifies the url of custom css which will display custom theme.

CustomClassName – This is required if user choose BalloonStyle to Custom. This specifies the name of the css class for the custom theme.

UseShadow – Optional setting specifying whether to display shadow of balloon popup or not.

ScrollBars – Optional setting specifying whether to display scrollbar if contents are overflowing. This property contains 5 options – None, Horizontal, Vertical, Both and Auto. Default value is Auto.

DisplayOnMouseOver – Optional setting specifying whether to display balloon popup on the client onMouseOver event. Default value is false.

DisplayOnFocus – Optional setting specifying whether to display balloon popup on the client onFocus event. Default value is false.

DisplayOnClick – Optional setting specifying whether to display balloon popup on the client onClick event. Default value is true.

Animations – Generic animations for the PopupControlExtender.

                     OnShow – The OnShow animation will be played each time the popup is displayed. The popup will be positioned correctly               but hidden. The animation can use <HideAction Visible=”true” /> to display the popup along with any other visual effects.

                     OnHide – The OnHide animation will be played each time the popup is hidden.


A very simple example for Balloon POPUP Extender in ASP.Net/C# using Ajax

Here we are demonstrating a very simple for implementing Ajax Balloon POPUP Extender  with full downloadable source code.

ASPX Page

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" 
AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="BaloonPopup._Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" 
TagPrefix="ajax" %>
<asp:Content ID="HeaderContent" runat="server" 
ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" 
ContentPlaceHolderID="MainContent">
<h2>
Welcome to Baloon Popup Extender Sample
</h2>
<p>
For Website/WebApplication creation <a href="http://www.tuvian.com" 
title="aps.net">www.tuvian.com</a>.
</p>
<div>
<ajax:ToolkitScriptManager ID="Scriptmanager1" runat="server">
</ajax:ToolkitScriptManager>
<div style="border: 1px solid gray; padding: 10px; margin: 10px;">
<h3>
Cloud Style Baloon Popup Example</h3>
<br />
<br />
<ajax:BalloonPopupExtender ID="PopupControlExtender2" runat="server" 
TargetControlID="txtUserName"
BalloonPopupControlID="pnlBalloon" Position="BottomRight" BalloonStyle="Cloud"
BalloonSize="Medium" UseShadow="true" ScrollBars="Auto" DisplayOnMouseOver="true"
DisplayOnFocus="false" DisplayOnClick="true" />
UserName :
<asp:TextBox runat="server" ID="txtUserName" />
<asp:Panel runat="server" ID="pnlBalloon">
This is the Cloud Style Ballon Popup</asp:Panel>
</div>
<div style="border: 1px solid gray; padding: 10px; margin: 10px;">
<h3>
Rectangular Baloon Popup Example</h3>
<br />
<br />
<ajax:BalloonPopupExtender ID="Balloonpopupextender1" runat="server" 
TargetControlID="lblShow"
BalloonPopupControlID="pnlRectangularBallon" Position="TopRight" 
BalloonStyle="Rectangle"
BalloonSize="Medium" UseShadow="true" ScrollBars="Auto" 
DisplayOnMouseOver="false"
DisplayOnFocus="false" DisplayOnClick="true" />
<asp:Label runat="server" ID="lblShow" 
Text="Click Here to Show the Rectangular Balloon Popup" />
<asp:Panel runat="server" ID="pnlRectangularBallon">
This is the rectangular ballon popup</asp:Panel>
</div>
<div style="border: 1px solid gray; padding: 10px; margin: 10px;">
<h3>
Custom Style Baloon Popup Example</h3>
<br />
<br />
<ajax:BalloonPopupExtender ID="Balloonpopupextender2" runat="server" 
TargetControlID="txtCustomBallonPopup"
BalloonPopupControlID="pnlCustomBallon" Position="BottomRight" 
BalloonStyle="Custom"
BalloonSize="Medium" UseShadow="true" ScrollBars="Auto" 
DisplayOnMouseOver="true"
CustomCssUrl="Styles/BalloonPopupOvalStyle.css" 
CustomClassName="oval" DisplayOnFocus="false"
DisplayOnClick="true" />
<asp:TextBox runat="server" ID="txtCustomBallonPopup" />
<asp:Panel runat="server" ID="pnlCustomBallon">
This is the Custom Style ballon popup</asp:Panel>
</div>
</div>
</asp:Content>
--------------

                  DOWNLOAD SOURCE CODE FOR BALLOON POPUP EXTENDER EXAMPLE

How to create always visible div using Ajax/ Always visible div in ASP.Net using Ajax

September 22, 2012 1 comment

                                  DOWNLOAD SOURCE CODE FOR ALWAYS VISIBLE DIV

Create very simple always visible div using ajax in ASP.Net

Here we are demonstrating how to create a very simple always visible div using Ajax in ASP.Net/C#. Some of the WebPages we may need to show some information always visible to user even they are scrolling down and up.   In this situation we can achieved it by different method. In our previous post we already posted how to create a always visible div using CSS. Here we are going to implement the always visible div using Ajax in ASP.Net/C#.

Register Ajax Control Toolkit

In order to implement always visible div using Ajax, we need to download and refer ajax control toolkit to our project. First of all download ajaxtoolkit dll from here and right click the ‘References’ under the ASP.Net project from Visual Studio and browse the dll and press OK.

In the ASPX page we need to register this ajax toolkit dll like below mentioned code.

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”ajax” %>

How to implement AlwaysVisibleControlExtender in AJAX Controls?

Always vissible Control Extender in Ajax control tool kit is using to implement always vissible div or any controls in ASP.Net/C#.

After registering the ajax control tool kit we can implement alwaysvisibleextender as below mentioned code.

<ajax:alwaysvisiblecontrolextender id="ace" runat="server" targetcontrolid="pnlTimer"
 verticalside="Top" verticaloffset="10" horizontalside="Right" horizontaloffset="10"
 scrolleffectduration=".1" />

We are having some properties in the alwaysvisiblecontrolextender and we can adjust the postion and controls for always visible extender. Below are the main properties of alwaysvissibleextender in ajax.

TargetControlID – ID of control for this extender to always make visible

HorizontalOffset – Distance to the HorizontalSide edge of the browser in pixels from the same side of the target control. The default is 0 pixels.

HorizontalSide – Horizontal edge of the browser (either Left, Center, or Right) used to anchor the target control. The default is Left.

VerticalOffset – Distance to the VerticalSide edge of the browser in pixels from the same side of the target control. The default is 0 pixels.

VerticalSide – Vertical edge of the browser (either Top, Middle, or Bottom) used to anchor the target control. The default is Top.

ScrollEffectDuration – Length in seconds of the scrolling effect to last when the target control is repositioned. The default is .1 second.

 ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="AjaxControls.aspx.cs" 
Inherits="ExperimentLab.AjaxControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" 
TagPrefix="ajax" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
 <ajax:ToolkitScriptManager ID="Scriptmanager1" runat="server">
 </ajax:ToolkitScriptManager>
 <div>
<ajax:AlwaysVisibleControlExtender id="ace" runat="server" 
targetcontrolid="pnlTimer"
 verticalside="Top" verticaloffset="10" horizontalside="Right" 
horizontaloffset="10"
 scrolleffectduration=".1" />
<div runat="server" id="pnlTimer" style="border: 2px solid green; 
height: 100px;
 width: 200px; text-align: center; padding-top: 50px; 
font-weight: bold;">
 This div is always visible to user
</div>
 <br />
 <br />
 Scroll down .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 Scroll down
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 Scroll down
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 .
 <br />
 Still 'Always visible div' is available ...!
 </div>
 </form>
</body>
</html>

------

                                                        DOWNLOAD SOURCE CODE FOR ALWAYS VISIBLE DIV


								

Example for All Types of SQL JOIN (Inner Join, Cross Join, Outer Join, Self Join)

September 9, 2012 Leave a comment

Definition and very simple examples for each JOINS in SQL

Here we are demonstrating with examples  all types of JOINS in SQL Server.  First of all we created sample tables and as per the table data we are explaining each SQL JOINS with most understandable examples.

Sample tables

In the following tables, Department.DepartmentID is the primary key, while Employee.DepartmentID is a foreign key.

Employee Table

LastName

DepartmentID

Rafferty

31

Jones

33

  Steinberg

33

Robinson

34

Smith

34

Jasper

NULL

Department Table

DepartmentID

DepartmentName

31

Sales

33

Engineering

34

Clerical

35

Marketing

Inner join

An inner join requires each record in the two joined tables to have a matching record. An inner join essentially combines the records from two tables (A and B) based on a given join-predicate. The result of the join can be defined as the outcome of first taking the Cartesian product (or cross-join) of all records in the tables (combining every record in table A with every record in table B) – then return all records which satisfy the join predicate.

SQL specifies two different syntactical ways to express joins. The first, called “explicit join notation”, uses the keyword JOIN, whereas the second uses the “implicit join notation”. The implicit join notation lists the tables for joining in the FROM clause of a SELECT statement, using commas to separate them. Thus, it specifies a cross-join, and the WHERE clause may apply additional filter-predicates. Those filter-predicates function comparably to join-predicates in the explicit notation.

One can further classify inner joins as equi-joins, as natural joins, or as cross-joins (see below).

Example of an explicit inner join:

SELECT *
FROM   employee
       INNER JOIN department
          ON employee.DepartmentID = department.DepartmentID
Is equivalent to:
SELECTFROM   employee, department
WHERE  employee.DepartmentID = department.DepartmentID

Explicit Inner join result:

Employee.

LastName

Employee.

DepartmentID

Department.

DepartmentName

Department.

DepartmentID

Smith

34

Clerical

34

Jones

33

Engineering

33

Robinson

34

Clerical

34

Steinberg

33

Engineering

33

Rafferty

31

Sales

31

Types of inner joins

Equi-join

An equi-join, also known as an equijoin, is a specific type of comparator-based join, or theta join, that uses only equality comparisons in the join-predicate. Using other comparison operators (such as <) disqualifies a join as an equi-join.

SELECT Employee.lastName, Employee.DepartmentID, Department.DepartmentName
FROM Employee INNER JOIN Department
ON Employee.DepartmentID = Department.DepartmentID;
SQL provides optional syntactic sugar for expressing equi-joins,
by way of the USING construct (Feature ID F402):
SELECT Employee.lastName, DepartmentID, Department.DepartmentName
FROM Employee INNER JOIN Department
USING(DepartmentID);

The USING clause is supported by MySQL, Oracle and PostgreSQL.

Natural join

A natural join offers a further specialization of equi-joins. The join predicate arises implicitly by comparing all columns in both tables that have the same column-name in the joined tables. The resulting joined table contains only one column for each pair of equally-named columns.

The above sample query for inner joins can be expressed as a natural join in the following way:

SELECT *
FROM   employee NATURAL JOIN department

The result appears slightly different, however, because only one DepartmentID column occurs in the joined table.

DepartmentID

Employee.LastName

Department.DepartmentName

34

Smith

Clerical

33

Jones

Engineering

34

Robinson

Clerical

33

Steinberg

Engineering

31

Rafferty

Sales

Cross join

cross joincartesian join or product provides the foundation upon which all types of inner joins operate. A cross join returns the cartesian product of the sets of records from the two joined tables. Thus, it equates to an inner join where the join-condition always evaluates to True or join-condition is absent in statement.

If A and B are two sets, then the cross join is written as A × B.

The SQL code for a cross join lists the tables for joining (FROM), but does not include any filtering join-predicate.

Example of an explicit cross join:

SELECT *
FROM   employee CROSS JOIN department

Example of an implicit cross join:

SELECT *

FROM   employee, department;

Employee.

LastName       

Employee.

DepartmentID 

Department.

DepartmentName

Department.

DepartmentID

Rafferty

31

Sales

31

Jones

33

Sales

31

Steinberg

33

Sales

31

Smith

34

Sales

31

Robinson

34

Sales

31

Jasper

NULL

Sales

31

Rafferty

31

Engineering

33

Jones

33

Engineering

33

Steinberg

33

Engineering

33

Smith

34

Engineering

33

Robinson

34

Engineering

33

Jasper

NULL

Engineering

33

Rafferty

31

Clerical

34

Jones

33

Clerical

34

Steinberg

33

Clerical

34

Smith

34

Clerical

34

Robinson

34

Clerical

34

Jasper

NULL

Clerical

34

Rafferty

31

Marketing

35

Jones

33

Marketing

35

Steinberg

33

Marketing

35

Smith

34

Marketing

35

Robinson

34

Marketing

35

Jasper

NULL

Marketing

35

Outer joins

An outer join does not require each record in the two joined tables to have a matching record. The joined table retains each record—even if no other matching record exists. Outer joins subdivide further into left outer joins, right outer joins, and full outer joins, depending on which table(s) one retains the rows from (left, right, or both).

Left outer join

The result of a left outer join (or simply left join) for tables A and B always contains all records of the “left” table (A), even if the join-condition does not find any matching record in the “right” table (B). This means that if the ON clause matches 0 (zero) records in B, the join will still return a row in the result—but with NULL in each column from B. This means that a left outer join returns all the values from the left table, plus matched values from the right table (or NULL in case of no matching join predicate).

SELECTFROM   employee  LEFT OUTER JOIN department 
          ON employee.DepartmentID = department.DepartmentID

Employee.

LastName

Employee.

DepartmentID

Department.

DepartmentName

Department.

DepartmentID

Jones

33

Engineering

33

Rafferty

31

Sales

31

Robinson

34

Clerical

34

Smith

34

Clerical

34

Jasper

NULL

NULL

NULL

Steinberg

33

Engineering

33

Right outer joins

right outer join (or right join) closely resembles a left outer join, except with the tables reversed. Every row from the “right” table (B) will appear in the joined table at least once. If no matching row from the “left” table (A) exists, NULL will appear in columns from A for those records that have no match in A.

A right outer join returns all the values from the right table and matched values from the left table (NULL in case of no matching join predicate).
SELECT *
FROM   employee RIGHT OUTER JOIN department
          ON employee.DepartmentID = department.DepartmentID

Employee.

LastName

Employee.

DepartmentID

Department.

DepartmentName

Department.

DepartmentID

Smith

34

Clerical

34

Jones

33

Engineering

33

Robinson

34

Clerical

34

Steinberg

33

Engineering

33

Rafferty

31

Sales

31

NULL

NULL

Marketing

35

In practice, explicit right outer joins are rarely used, since they can always be replaced with left outer joins and provide no additional functionality.

Full outer join

full outer join combines the results of both left and right outer joins. The joined table will contain all records from both tables, and fill in NULLs for missing matches on either side.

For example, this allows us to see each employee who is in a department and each department that has an employee, but also see each employee who is not part of a department and each department which doesn’t have an employee.

Example full outer join:

SELECT *    
FROM   employee
       FULL OUTER JOIN department
          ON employee.DepartmentID = department.DepartmentID

Employee.

LastName

Employee.

DepartmentID

Department.

DepartmentName

Department.

DepartmentID

Smith

34

Clerical

34

Jones

33

Engineering

33

Robinson

34

Clerical

34

Jasper

NULL

NULL

NULL

Steinberg

33

Engineering

33

Rafferty

31

Sales

31

NULL

NULL

Marketing

35

 

Self-join

A self-join is joining a table to itself.

Example

A query to find all pairings of two employees in the same country is desired. If you had two separate tables for employees and a query which requested employees in the first table having the same country as employees in the second table, you could use a normal join operation to find the answer table. However, all the employee information is contained within a single large table.

Considering a modified Employee table such as the following:

Employee Table

EmployeeID

LastName

Country

DepartmentID

123

Rafferty

Australia

31

124

Jones

Australia

33

145

Steinberg

Australia

33

201

Robinson

United States

34

305

Smith

United Kingdom

34

306

Jasper

United Kingdom

NULL

An example solution query could be as follows:

SELECT F.EmployeeID, F.LastName, S.EmployeeID, S.LastName, F.Country
FROM Employee F, Employee S
WHERE F.Country = S.Country
AND F.EmployeeID < S.EmployeeID
ORDER BY F.EmployeeID, S.EmployeeID;

Which results in the following table being generated.

Employee Table after Self-join by Country

EmployeeID

LastName

EmployeeID

LastName

Country

123

Rafferty

124

Jones

Australia

123

Rafferty

145

Steinberg

Australia

124

Jones

145

Steinberg

Australia

305

Smith

306

Jasper

United Kingdom

 

How to Create a Data Table Dynamically with sample data and Bind to Grid/Create datatable with sample data.

September 7, 2012 Leave a comment

How to create a datatable with sample data

We are going to demonstrate how to create a sample datatable dynamically in ASP.Net. Here we are creating a ASPx page with a grid view. In the page load of the ASPx page will call a bind method which creating a datatable dynamically and bind the datatable with datagrid. In BindGridviewData function create data for an employee and binding employee data to the employee grid.

ASPxPage

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicCreateDataTable.aspx.cs"
    Inherits="ExperimentLab.DynamicCreateDataTable" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gdEmployee" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Code Behind

protected void Page_Load(object sender, EventArgs e)
{
BindGridviewData();
}
//Creating datatable dynamically and bind data to a grid
protected void BindGridviewData()
{
DataTable dt = new DataTable();
//Create datatable Columns dynamically 
dt.Columns.Add("EmployeeID", typeof(Int32));
dt.Columns.Add("EmployeeName", typeof(string));
dt.Columns.Add("Department", typeof(string));
dt.Columns.Add("City", typeof(string));
//Create data table row dynamically add
DataRow dtrow = dt.NewRow(); // Create New Row 
//Assign data to datarow dynamically
dtrow["EmployeeID"] = 1; //Bind Data to Columns
dtrow["EmployeeName"] = "Ramraj";
dtrow["Department"] = "Admin";
dtrow["City"] = "Calicut";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); // Create New Row
//Assign data to datarow dynamically
dtrow["EmployeeID"] = 2; //Bind Data to Columns
dtrow["EmployeeName"] = "Malhothra";
dtrow["Department"] = "HR";
dtrow["City"] = "Mumbai";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); // Create New Row
//Assign data to datarow dynamically
dtrow["EmployeeID"] = 3; //Bind Data to Columns
dtrow["EmployeeName"] = "Sinan Hafis";
dtrow["Department"] = "Admin";
dtrow["City"] = "Delhi";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); // Create New Row
//Assign data to datarow dynamically
dtrow["EmployeeID"] = 4; //Bind Data to Columns
dtrow["EmployeeName"] = "Wazim Jafar";
dtrow["Department"] = "Finance";
dtrow["City"] = "Goa";
dt.Rows.Add(dtrow);
gdEmployee.DataSource = dt;
gdEmployee.DataBind();
}

RESULT 

Dynamic datatable in ASP.Net

Dynamic datatable in ASP.Net

Follow

Get every new post delivered to your Inbox.

Join 29 other followers

%d bloggers like this: