Monday, December 26, 2011

Generate five digit Random Number

public string GetRandomString(int seed)
    {
        //use the following string to control your set of alphabetic characters to choose from
        //for example, you could include uppercase too
        const string alphabet = "abcdefghijklmnopqrstuvwxyz";

        // Random is not truly random,
        // so we try to encourage better randomness by always changing the seed value
        Random rnd = new Random((seed + DateTime.Now.Millisecond));

        // basic 5 digit random number
        string result = rnd.Next(10000, 99999).ToString();

        // single random character in ascii range a-z
        string alphaChar = alphabet.Substring(rnd.Next(0, alphabet.Length-1),1);

        // random position to put the alpha character
        int replacementIndex = rnd.Next(0, (result.Length - 1));
        result = result.Remove(replacementIndex, 1).Insert(replacementIndex, alphaChar);

        return result;
    }

Import Excel Data Into An ASP.NET GridView using OLEDB

using System.Data.OleDb;
using System.Data;
public partial class UploadD : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e)
{
string cnstr = “Provider=Microsoft.Jet.Oledb.4.0;Data Source=C:\a.xls;”+ “Extended Properties=Excel 8.0″;
OleDbConnection oledbConn = new OleDbConnection(cnstr);
string strSQL = “SELECT * FROM [Sheet$]“;
OleDbCommand cmd = new OleDbCommand(strSQL, oledbConn);
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}

Payment gateway implementation C# in asp.Net

Copy paste following code to implement payment gateway using c#.net:
String post_url = “https://test.authorize.net/gateway/transact.dll“;
Hashtable post_values = new Hashtable();
//the API Login ID and Transaction Key must be replaced with valid values
post_values.Add(“x_login”, “6zz6m5N4Et”);
post_values.Add(“x_tran_key”, “9V9wUv6Yd92t27t5″);
post_values.Add(“x_delim_data”, “TRUE”);
post_values.Add(“x_delim_char”, ‘|’);
post_values.Add(“x_relay_response”, “FALSE”);
post_values.Add(“x_type”, “AUTH_CAPTURE”);
post_values.Add(“x_method”, “CC”);
post_values.Add(“x_card_num”, “378282246310005″);
post_values.Add(“x_exp_date”, “0809″);
post_values.Add(“x_amount”, “99999.00″);
post_values.Add(“x_description”, “Sample Transaction”);
post_values.Add(“x_first_name”, “John”);
post_values.Add(“x_last_name”, “Doe”);
post_values.Add(“x_address”, “1234 Street”);
post_values.Add(“x_state”, “WA”);
post_values.Add(“x_zip”, “98004″);
// Additional fields can be added here as outlined in the AIM integration
// guide at: http://developer.authorize.net
// This section takes the input fields and converts them to the proper format
// for an http post. For example: “x_login=username&x_tran_key=a1B2c3D4″
String post_string = “”;
foreach(DictionaryEntry field in post_values)
{
post_string += field.Key + “=” + field.Value + “&”;
}
post_string = post_string.TrimEnd(‘&’);

// create an HttpWebRequest object to communicate with Authorize.net
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(post_url);
objRequest.Method = “POST”;
objRequest.ContentLength = post_string.Length;
objRequest.ContentType = “application/x-www-form-urlencoded”;
// post data is sent as a stream
StreamWriter myWriter = null;
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(post_string);
myWriter.Close();
// returned values are returned as a stream, then read into a string
String post_response;
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()) )
{
post_response = responseStream.ReadToEnd();
responseStream.Close();
}
// the response string is broken into an array
// The split character specified here must match the delimiting character specified above
Array response_array = post_response.Split(‘|’);
// the results are output to the screen in the form of an html numbered list.
resultSpan.InnerHtml += “<OL> \n”;
foreach (string value in response_array)
{
resultSpan.InnerHtml += “<LI>” + value + “&nbsp;</LI> \n”;
}
resultSpan.InnerHtml += “</OL> \n”;
// individual elements of the array could be accessed to read certain response
// fields. For example, response_array[0] would return the Response Code,
// response_array[2] would return the Response Reason Code.
// for a list of response fields, please review the AIM Implementation Guide

Monday, November 21, 2011

Stored Procedure (Create autogenerate column in table & Fetch data)By Cursor--Best Use of cursor

CREATE  PROC SP_FINAL_REPORT_NS_KG  --SP_FINAL_REPORT_NS_KG 2,13,'A',6,'satyam',1   
(@SessionId int,@ClassId int,@Section varchar(2),     
 @TestTypeId int,@UserId varchar(40),@Criteria int     
)      
AS BEGIN       
IF(@Criteria=1)     
BEGIN     
------------------------------------       
CREATE TABLE #TMP       
(       
ID INT NULL,SNAME VARCHAR(50) NULL       
)       
INSERT INTO #TMP EXEC sp_getacademicsubject @UserId,@SessionId,@ClassId ---'Devender',2,13       
--SELECT * FROM #TMP       
------------------------------------       
CREATE TABLE #TMP1       
(ROLLNO INT NULL,STUDENT_ID INT NULL,       
 STUDENT_NAME VARCHAR(50) NULL)       
       
DECLARE @SQL NVARCHAR(1000)       
DECLARE @COLS NVARCHAR(1000)        
DECLARE @SNAME VARCHAR(25)       
       
DECLARE CUR_SUB CURSOR FAST_FORWARD FOR       
SELECT SNAME FROM #TMP       
OPEN CUR_SUB       
FETCH NEXT FROM CUR_SUB INTO @SNAME       
 WHILE(@@FETCH_STATUS=0)       
 BEGIN       
  SET @COLS=@SNAME + ' ' + 'VARCHAR(5)'        
  SELECT  @SQL='ALTER TABLE #TMP1 ADD ' + @COLS       
  EXEC(@SQL)       
FETCH NEXT FROM CUR_SUB INTO @SNAME       
END       
 PRINT @sql     
 CLOSE CUR_SUB                                             
 DEALLOCATE CUR_SUB         
-------------------------------------       
DECLARE @SID INT       
DECLARE @LEN INT       
DECLARE @OBT_MARKS VARCHAR(8)       
DECLARE @GRADE VARCHAR(5)       
DECLARE @EVL_TYPE_ID VARCHAR(2)       
DECLARE @STUDENTID VARCHAR(10)       
DECLARE @ROLLNO VARCHAR(5)        
DECLARE @STUDENT_NAME VARCHAR(50)       
SET @COLS=NULL       
SET @SQL=NULL       
       
DECLARE MAIN_CURSOR CURSOR FAST_FORWARD FOR       
  select distinct STM.Current_RollNo,SM._studentID,SM._studentname                         
  from tbl_StudentMaster SM INNER JOIN                          
  student_table_sessionwise STM on SM._studentID=STM.Student_Id                         
  where STM.SessionId=@SessionId and STM.Class=@ClassId  and STM.section=@Section                       
         
 OPEN MAIN_CURSOR        
 FETCH NEXT FROM MAIN_CURSOR INTO @ROLLNO,@STUDENTID,@STUDENT_NAME       
 WHILE (@@FETCH_STATUS=0)       
 BEGIN     
      
      ---------------------------------------------------------------------       
      DECLARE @COLL VARCHAR(1000)     
      SET @COLL=''    SET @SQL=''     
      DECLARE EX_CURSOR CURSOR FAST_FORWARD FOR       
      SELECT ID FROM #TMP        
      OPEN EX_CURSOR        
      FETCH NEXT FROM EX_CURSOR INTO @SID       
      WHILE (@@FETCH_STATUS=0)       
      BEGIN       
                  
           SELECT @OBT_MARKS=_OBT_MARKS,@GRADE=_GRADE,       
           @EVL_TYPE_ID=_EVL_TYPE_ID FROM        
           tbl_add_Marks_NS_KG WHERE  _academicId=@SessionId AND        
           _test_typeID=@TestTypeId AND _classID=@ClassId  AND        
           _studentId=@STUDENTID AND _subjectId=@SID       
           
            SET @OBT_MARKS=ISNULL(@OBT_MARKS,'0')   
            IF(@OBT_MARKS='0')   
            BEGIN   
            SET @OBT_MARKS=ISNULL(@GRADE,'')   
            END   
      
      
            SET @COLL=@COLL + ''''+@OBT_MARKS+''''+','    
   
            SET @OBT_MARKS=NULL       SET @EVL_TYPE_ID=NULL     
            SET @GRADE=NULL           SET @SID=NULL    
          
      FETCH NEXT FROM EX_CURSOR INTO @SID       
      END            
           
      SET @LEN=LEN(@COLL)       
      SET @COLL=SUBSTRING(@COLL,1,LEN(@COLL)-1)   
      set @ROLLNO=ISNULL(@ROLLNO,'')     
      SET @SQL='insert INTO #TMP1 VALUES('''+@ROLLNO+''','''+@STUDENTID+''','''+@STUDENT_NAME+''','+@COLL+')'       
      EXEC(@SQL)     
           
      CLOSE EX_CURSOR                                             
      DEALLOCATE EX_CURSOR        
    -----------------------------------------------------------------------------       
   SET @ROLLNO=NULL     SET @STUDENTID=NULL             SET @STUDENT_NAME=NULL         
   FETCH NEXT FROM MAIN_CURSOR INTO @ROLLNO,@STUDENTID,@STUDENT_NAME         
   END       
   CLOSE MAIN_CURSOR                                             
   DEALLOCATE MAIN_CURSOR        
        
 SELECT * FROM #TMP1 ORDER BY STUDENT_NAME ASC    
END       
END

Wednesday, September 7, 2011

Download PDF/Doc File from Web (asp.net,c#)

Client side Code
------------------------------------------------------------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!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="gvtest" runat="server" AutoGenerateColumns ="false">
    <Columns>
    <asp:TemplateField HeaderText="S.No.">
    <ItemTemplate >
    <%#Container.DataItemIndex+1 %>
    </ItemTemplate>
    </asp:TemplateField>
   
    <asp:TemplateField HeaderText="Link">
    <ItemTemplate >
    <asp:LinkButton ID="lnk" runat="server" Text="download" OnClick="lnk_Click" ToolTip='<%#Eval("LinkId")%>'></asp:LinkButton>
    </ItemTemplate>
    </asp:TemplateField>
   
    </Columns>
    </asp:GridView>
    </div>
    </form>
</body>
</html>
-----Code Behind---------------------------------------------------------------------
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            gvtest.DataSource = bindGrid();
            gvtest.DataBind();
        }
    }
    protected void lnk_Click(object sender, EventArgs e)
    {
        LinkButton lnkbutton = (LinkButton)sender;
        string id = lnkbutton.ToolTip.ToString();
        String fileName=id.ToString()+".pdf";
        FileInfo fl = new FileInfo(Server.MapPath("PDF/" +fileName ));
        if (fl.Exists)
        {
                    Response.ClearContent();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                    Response.AddHeader("Content-Length", fileName.Length.ToString());  
                    string CId = Request["__EVENTTARGET"];
                    Response.TransmitFile(fl.FullName);  
                    Response.End();  
                    //string path = fl.ToString();
                    //ScriptManager.RegisterStartupScript(Page, GetType(), "rs", "window.open('" + fl + "');", true);
        }
    }
    protected DataTable   bindGrid()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("LinkId");
        for (int i = 1; i <5; i++)
        {
            DataRow dr = dt.NewRow();
            dr["LinkId"] = i.ToString();
            dt.Rows.Add(dr);
            dt.AcceptChanges();
        }
        return dt;
    }
}



Transaction in C# with Sql-Server Code behind







using System;
using System.Data.SqlClient;

namespace CsharpWebApp
{
    public class TransactionDemo
    {
        public TransactionDemo()
        {

        }

        [STAThread]
        public static void Main()
        {
            Demo1();
        }

        private static void Demo1()
        {
            SqlConnection dbConn = new SqlConnection("sqlConnectionString");
            SqlTransaction transaction;

            dbConn.Open();
            transaction = dbConn.BeginTransaction();

            SqlCommand sqlDept = new SqlCommand("INSERT INTO EmployeeDepartment (EmpId, Department) VALUES (1,

'Department');", dbConn, transaction);
            SqlCommand sqlManager = new SqlCommand("INSERT INTO EmployeeManager (EmpId, Manager) VALUES (1,

'Department');", dbConn, transaction);

            try
            {
                sqlDept.ExecuteNonQuery();
                sqlManager.ExecuteNonQuery();
                transaction.Commit();
            }
            catch (SqlException sqlError)
            {
                transaction.Rollback();
            }
            finally
            {
                dbConn.Close();
                sqlDept.Dispose();
                sqlManager.Dispose();
                dbConn.Dispose();
            }
          
        }
    }

Wednesday, August 10, 2011

Generate Random Numbers using C#

Random randNum = new Random();
randNum.Next();

That's all it takes. The creation of a Random object (of the System.Random class) and calling its Next() method, which is going to return a non-negative random number as an integer.
EX:
Random randNum = new Random();
randNum.Next(108); // No larger than 108
randNum.Next(1, 108); // No larger than 108, no smaller than 1

Get the IP address in a Web/Windows application

using System.Net;
private void button1_Click(object sender, EventArgs e)
{

string myHost = System.Net.Dns.GetHostName();
string myIp = System.Net.Dns.GetHostEntry(myHost).AddressList[0].ToString();

richTextBox1.Text = (myHost);
richTextBox2.Text = (myIp);

}

Friday, August 5, 2011

Design Pattern (Abstract Factory Pattern) Hi Friends U can get help from this


Design Pattern (Abstract Factory Pattern)
Hi Friends U can get help from this
The intent of abstract factory Pattern is to provide interface of creating family of related or dependent object without specifying concert product class.
Let’s take example for developing web and windows application control. We have factory for Button controls having WebButton, WindowsButton and we have factory for TextBox control  WebTextBox, WindowsTextBox.  Now I want to create object for web or windows without specifying there concrete classes. In this situation I will use abstract factory.
The participant in the Abstract factory Pattern:
  • AbstractFactory: declare interface that create abstract product. In our example Application is AbstractFactory class.
  • ConcreteFactory: implement operation to create concrete product object. In our case webApplication and WindowApplication is ConcreteFactory
  • AbstractProduct: Declare interface for type of product. In our case control is Abstract product.
  • Product: define product which is created by correspondent ConcreteFactory. In our example Button and TextBox is Prroduct.
  • Client: use interface declare by abstractFactory and AbstractProduct classes.
Class Implementation
namespace FactoryPattern
{
      ///
      ///
Abstract Factory Class
      ///
      public abstract class MyApplicationFactory
      {
         public abstract MyButton CreateButton();
         public abstract MyTextBox CreateText();
      }
      ///
      ///
ConcreteFactory Class1
      ///
      public class WebFactory : MyApplicationFactory
      {
         public override MyButton CreateButton()
         {
            return new WebButton();
         }
         public override MyTextBox CreateText()
         {
            return new WebTextBox();
         }
      }
      ///
      ///
ConcreteFactory Class2
      ///
      public class WindowFactory : MyApplicationFactory
      {
         public override MyButton CreateButton()
         {
            return new WindowButton();
         }
         public override MyTextBox CreateText()
         {
            return new WindowTextBox();
         }
      }
      ///
      ///
Abstract product 1
      ///
      public abstract class MyButton
      
{
            public abstract void GetInformation();
      }
      ///
      ///
Abstract product 2
      ///
      public abstract class MyTextBox
      {
         public abstract void GetInformation();
      }
      ///
      ///
Product 1.1
      ///
      public class WebButton: MyButton
      {
         public override void GetInformation()
         {
            Console.Write("\nWebButton");
         }
      }
      ///
      ///
Product 1.2
      ///
      public class WindowButton : MyButton
      {
         public override void GetInformation()
         {
            Console.Write("\nWindowButton");
         }
      }
      ///
      ///
Product 2.1
      ///
      public class WebTextBox : MyTextBox
      {
         public override void GetInformation()
         {
            Console.Write("\nWebTextBox");
         }
      }
      ///
      ///
Product 2.2
      ///
      public class WindowTextBox : MyTextBox
      {
         public override void GetInformation()
         {
            Console.Write("\nWindowTextBox");
         }
      }
      ///
      ///
Client Class
      ///
      public class MyApplication
      {
         MyButton _button;
         MyTextBox _textbox;
         public MyApplication(MyApplicationFactory objFactory)
         {
            _button = objFactory.CreateButton();
            _textbox = objFactory.CreateText();
         }
         public void GetDetail()
         {
            _button.GetInformation();
            _textbox.GetInformation();
         }
      }
}

with thanks
RS Prajapati

SQL-Server 2008 R New Feature

Database Engine iconDatabase EngineThe Database Engine is the core service for storing, processing and securing data. The Database Engine provides controlled access and rapid transaction processing to meet the requirements of the most demanding data consuming applications within your enterprise. The Database Engine also provides rich support for sustaining high availability.
Analysis Services iconAnalysis Services - Multidimensional DataAnalysis Services supports OLAP by allowing you to design, create, and manage multidimensional structures that contain data aggregated from other data sources, such as relational databases.
Data mining iconAnalysis Services - Data MiningAnalysis Services enables you to design, create, and visualize data mining models. These mining models can be constructed from other data sources by using a wide variety of industry-standard data mining algorithms.
Integration Services iconIntegration ServicesIntegration Services is a platform for building high performance data integration solutions, including packages that provide extract, transform, and load (ETL) processing for data warehousing.
Master Data Services icon
Master Data Services Master Data Services is the source of master data for your organization. By integrating disparate operational and analytic systems with Master Data Services, you ensure that all applications across the organization rely on a central, accurate source of information. Using Master Data Services, you create a single source of master data and maintain an auditable record of that data as it changes over time.
Replication iconReplicationReplication is a set of technologies for copying and distributing data and database objects from one database to another, and then synchronizing between databases to maintain consistency. By using replication, you can distribute data to different locations and to remote or mobile users by means of local and wide area networks, dial-up connections, wireless connections, and the Internet.
Reporting Services iconReporting ServicesReporting Services delivers enterprise, Web-enabled reporting functionality so you can create reports that draw content from a variety of data sources, publish reports in various formats, and centrally manage security and subscriptions.
ms130214.SharePoint_icon(en-us,SQL.105).gif
SharePoint IntegrationSQL Server 2008 R2 offers new self-service business intelligence capability through integration with SharePoint products and technologies. In this release, both Analysis Services and Reporting Services support deployment in a SharePoint farm.
Service Broker iconService BrokerService Broker helps developers build scalable, secure database applications. This new Database Engine technology provides a message-based communication platform that enables independent application components to perform as a functioning whole. Service Broker includes infrastructure for asynchronous programming that can be used for applications within a single database or a single instance, and also for distributed applications.

Generate Dynamic Table ,Column by Using Cusor (Binging data for Gridview )

CREATE  PROC SP_FINAL_REPORT
(@SessionId int,@ClassId int,@Section varchar(2), 
 @TestTypeId int,@UserId varchar(40),@Criteria int 

/*-------------------------------
Writer :RS Prajapati
Profile:Software Engineer
Date: 05/08/2011
*/
AS BEGIN   
IF(@Criteria=1) 
BEGIN 
------------------------------------   
CREATE TABLE #TMP   
(   
ID INT NULL,SNAME VARCHAR(50) NULL   
)   
INSERT INTO #TMP EXEC sp_getacademicsubject @UserId,@SessionId,@ClassId ---'Devender',2,13   
--SELECT * FROM #TMP   
------------------------------------   
CREATE TABLE #TMP1   
(ROLLNO INT NULL,STUDENT_ID INT NULL,   
 STUDENT_NAME VARCHAR(50) NULL)   
   
DECLARE @SQL NVARCHAR(1000)   
DECLARE @COLS NVARCHAR(1000)    
DECLARE @SNAME VARCHAR(25)   
   
DECLARE CUR_SUB CURSOR FAST_FORWARD FOR   
SELECT SNAME FROM #TMP   
OPEN CUR_SUB   
FETCH NEXT FROM CUR_SUB INTO @SNAME   
 WHILE(@@FETCH_STATUS=0)   
 BEGIN   
  SET @COLS=@SNAME + ' ' + 'VARCHAR(5)'    
  SELECT  @SQL='ALTER TABLE #TMP1 ADD ' + @COLS   
  EXEC(@SQL)   
FETCH NEXT FROM CUR_SUB INTO @SNAME   
END   
 PRINT @sql 
 CLOSE CUR_SUB                                         
 DEALLOCATE CUR_SUB     
-------------------------------------   
DECLARE @SID INT   
DECLARE @LEN INT   
DECLARE @OBT_MARKS VARCHAR(5)   
DECLARE @GRADE VARCHAR(5)   
DECLARE @EVL_TYPE_ID INT   
DECLARE @STUDENTID VARCHAR(10)   
DECLARE @ROLLNO VARCHAR(5)    
DECLARE @STUDENT_NAME VARCHAR(50)   
SET @COLS=NULL   
SET @SQL=NULL   
   
DECLARE MAIN_CURSOR CURSOR FAST_FORWARD FOR   
  select distinct STM.Current_RollNo,SM._studentID,SM._studentname                     
  from tbl_StudentMaster SM INNER JOIN                      
  student_table_sessionwise STM on SM._studentID=STM.Student_Id                     
  where STM.SessionId=@SessionId and STM.Class=@ClassId  and STM.section=@Section                   
     
 OPEN MAIN_CURSOR    
 FETCH NEXT FROM MAIN_CURSOR INTO @ROLLNO,@STUDENTID,@STUDENT_NAME   
 WHILE (@@FETCH_STATUS=0)   
 BEGIN   
      ----------------------------------------------   
      DECLARE @COLL VARCHAR(2000) 
      SET @COLL=''   
      DECLARE EX_CURSOR CURSOR FAST_FORWARD FOR   
      SELECT ID FROM #TMP    
      OPEN EX_CURSOR    
      FETCH NEXT FROM EX_CURSOR INTO @SID   
      WHILE (@@FETCH_STATUS=0)   
      BEGIN   
              
        SELECT @OBT_MARKS=_OBT_MARKS,@GRADE=_GRADE,   
        @EVL_TYPE_ID=_EVL_TYPE_ID FROM    
        tbl_add_Marks_NS_KG WHERE  _academicId=@SessionId AND    
        _test_typeID=@TestTypeId AND _classID=@ClassId  AND    
        _studentId=@STUDENTID AND _subjectId=@SID   
        IF(@EVL_TYPE_ID=1)   
        begin   
        select @COLL=@COLL + ''''+@OBT_MARKS+''''+','   
        end   
        else   
        begin   
        select @COLL=@COLL + ''''+@GRADE+''''+','   
        end   
      
      SET @SID=NULL   
      FETCH NEXT FROM EX_CURSOR INTO @SID   
      END        
       
      SET @LEN=LEN(@COLL)   
      SET @COLL=SUBSTRING(@COLL,1,LEN(@COLL)-1) 
      SET @SQL='insert INTO #TMP1 VALUES('''+@ROLLNO+''','''+@STUDENTID+''','''+@STUDENT_NAME+''','+@COLL+')'   
      PRINT @SQL   
      EXEC(@SQL)   
      CLOSE EX_CURSOR                                         
      DEALLOCATE EX_CURSOR    
      --insert INTO #TMP1 VALUES(@ROLLNO,@STUDENTID,@STUDENT_NAME)   
      ----------------------------------------------   
   SET @ROLLNO=NULL     SET @STUDENTID=NULL             SET @STUDENT_NAME=NULL     
   FETCH NEXT FROM MAIN_CURSOR INTO @ROLLNO,@STUDENTID,@STUDENT_NAME     
   END   
   CLOSE MAIN_CURSOR                                         
   DEALLOCATE MAIN_CURSOR    
    
 SELECT * FROM #TMP1   
END   
END 

Merge Merging GridView Header Columns or multiple Headers ASP.NET C#

 
[GridHeader.JPG] 
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grvMergeHeader" runat="server"
BackColor="LightGoldenrodYellow"
BorderColor="Tan" BorderWidth="5px"
CellPadding="3" ForeColor="Black"
GridLines="None" BorderStyle="None"
CellSpacing="2"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
OnRowCreated="grvMergeHeader_RowCreated">
<FooterStyle BackColor="Tan" />
<SelectedRowStyle BackColor="DarkSlateBlue"
ForeColor="GhostWhite" />
<PagerStyle BackColor="PaleGoldenrod"
ForeColor="DarkSlateBlue"
HorizontalAlign="Center" />
<HeaderStyle BackColor="Tan" Font-Bold="True" />
<AlternatingRowStyle BackColor="PaleGoldenrod" />
<Columns>
<asp:BoundField DataField="DepartMentID"
HeaderText="DepartMentID"
SortExpression="DepartMentID" />
<asp:BoundField DataField="DepartMent"
HeaderText="DepartMent"
SortExpression="DepartMent" />
<asp:BoundField DataField="Name"
HeaderText="Name"
SortExpression="Name" />
<asp:BoundField DataField="Location"
HeaderText="Location"
SortExpression="Location" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [DepartMentID],
[DepartMent], [Name], [Location] FROM [Employee]">
</asp:SqlDataSource>
&nbsp;</div>
</form>
</body>
</html>
============================================================================
Now In Code behind, in RowCreated Event of grid view i m creating a new gridview row of header type and than in this row i m adding 2 cells 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void grvMergeHeader_RowCreated
(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView HeaderGrid = (GridView)sender;
GridViewRow HeaderGridRow =
new GridViewRow(0, 0, DataControlRowType.Header,
DataControlRowState.Insert);
TableCell HeaderCell = new TableCell();
HeaderCell.Text = "Department";
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);

HeaderCell = new TableCell();
HeaderCell.Text = "Employee";
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);

grvMergeHeader.Controls[0].Controls.AddAt
(0, HeaderGridRow);

}
}
}

Merge Merging GridView Header Columns or multiple Headers ASP.NET C#


Implementing Service Locator (To Resolve Dependency)

using System; /// <summary> /// Summary description for Class1 /// </summary> public class serviceLocator {     public s...