Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Dec 11, 2012

Consuming a web service using ASP .NET

To know about basics of web service read this article.
To know about creating a web service using ASP .NET read this article.

Background:
In the previous article we have learned about creating a web service. Now in this article, we will learn how to consume a web service using asp .NET.
Real Time Example:
Nowadays mobile application (Mobile Apps) are used widely all the users. Take a scenario, we install the “Weather” gadget in our mobile and check the weather of a particular place.
Think where we are receiving this weather information? It is actually we are consuming the web services.
We will select the region/place to see the weather, a web service will be called and the weather info is displayed.
Hence, Web Services are hosted somewhere and via internet we are consuming the data through the web service.

Implementation:
1. Create an ASP .NET web application with a simple design as shown below:
2. Now, we have to add the web service reference to this Project (Here we use the web service created in the previous article). Click on the Projects in solution explorer -> Add web reference -> give the url of the web service
(Note: to access the web service in the client use the appropriate machine/domain name)
Now, you will see the following screen:
3. Click on Go and search the web service and then give the web reference name say “Consume Service” in our example. Then click Add Reference button.
4. Now, in the solution explorer you will see the Web Reference being added as shown below:
5. We can use the methods exposed by the web service in our code and test the result. Sample code is shown below:
public partial class _Default : System.Web.UI.Page 
{
   protected void Page_Load(object sender, EventArgs e)
   {
   }
    protected void btnToCelsius_Click(object sender, EventArgs e)
    {
        double x = Convert.ToDouble(txtValue.Text);
        if(txtValue.Text != string.Empty)
        {
            try
            {
                ConsumeService.Service service = new ConsumeService.Service();

                lblOutput.Text = service.ToCelsius(x).ToString();                
                
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
    protected void btnToFahreinheit_Click(object sender, EventArgs e)
    {
        double x = Convert.ToDouble(txtValue.Text);

        if (txtValue.Text != string.Empty)
        {
            try
            {
                ConsumeService.Service service = new ConsumeService.Service();

                lblOutput.Text = service.ToFahreinheit(x).ToString();

            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

6. Build and run the code. Test the result by giving some inputs as shown below:

The whole source code can be downloaded from this link.

Hope the three articles about the web services explained about the basics of web services, creating and consuming the web services using ASP .NET in a simple way.
Please free to comment which help me to write more.

Creating Web Service using ASP .NET

To know about basics of web service read this article.

1.   Create an ASP .NET web service application using Microsoft Visual Studio.
2. Take a scenario that we have to convert Celsius to Fahrenheit and vice versa.
3.   Below is the code for our scenario:
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://ConversionWebService.org/Temp")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }
    [WebMethod(Description = "Convert Celsius to Fahreinheit")]
    public double ToFahreinheit(double C)
    {
        return C * (9.0/5.0) + 32;        
    }

    [WebMethod(Description = "Convert Fahreinheit to Celsius")]
    public double ToCelsius(double F)
    {
        return (F - 32) * (5.0/9.0);        
    }
   }
4. Build and run the web service, you will see the following output:
5.Now, we will test the web service by giving input values and invoke it.Below are the screen shots which will show the input given and the results:


                             
Hope this article, explains you about creating and running a simple web service using ASP .NET
Here is the link to download the full source code.

To know about consuming a web service using ASP .NET read this article.

Jul 1, 2012

Visual Studio Workflow in SharePoint

Part II
To know about the Basics and Advantages of using Visual Studio Workflow
read this article.
In this article, we will how to Create a Simple Sequential Workflow Console Application.
Steps:
1. Open Microsoft Visual Studio -> File -> New Project -> Select Visual C# -> SharePoint -> Workflow -> SequentialWorkflowConsoleApplication

2.  You can see the required DLL’s added in the solution for running the work flow in the Solution Explorer

3.  From the Toolbox -> Select Code -> drag and drop inside the designer view as shown below. Double Click on the codeActivity1 -> you will be navigated to Code behind page of the solution.


4. I have initialized a variable with get and set methods and activity for the code1 as shown below:

5. Now, go to the Design view -> From Toolbox -> Drag and drop IF ELSE activity and the code activity for IF and ELSE branch

6. Right click on codeActivity2 and click Generate handlers to create handlers the activity and do the same for codeActivity3
7. Now, we will set the condition for the ifElseActivity1 and 2. Right Click on ifElseActivity1 -> Properties -> Condition -> Select Declarative Rule Condition


8. Give the Condition Name and then Click on Expression for setting the condition:
9. Following are the conditions set for both the activities:


10.Now,if you click on any one of the activity -> properties -> select the name
then -> you can see the two conditions being used in the solution as shown:

11. Finally, I have added the message to be returned for the both activities

12. Now build the solution and then execute the code:

Here is the full solution. Click to download. Happy Sharing!
Hope, you have enjoyed this article.
Please free to comment and share this article, if it helps you!
Happy Coding!!

Jun 8, 2012

Internal Column Name in SharePoint List

In this article, we will know how to find the Internal Column Name in a SharePoint list.
Steps:
1. Suppose that we have created a list with a column named “Continent” as shown below:
2. Go to Settings-> List Settings -> Click on the Column listed in the Lists to which you have to find the Internal Name
3. You will be navigated to the Title Edit page which is shown below:
4. Now copy the Browser URL (in my case is something is shown below):
http://sitename/_layouts/FldEdit.aspx?List=%7BE62DB5A7%2D12D4%2D474B%2D8EB8%2DF71DE8A86723%7D&Field=Continent
The Bolded letter is the Internal Name of the Column (In my case Continent is the internal column name for the column Continent)
Note: 
If the column name contains spaces then the Internal Name will contain some other characters. Be careful while taking handling this:
Ex: http://SiteName/_layouts/FldEdit.aspx?List=%7B2EB82952%2D9C0B%2D4650%2DB5E9%2D22788822B1AA%7D&Field=Arrived%5Fx0020%5Fon
Here in this name %5F is a '_'
So the Internal Name would be Arrived_x0020_on. Here the Column name is Arrived On but the Internal Name is different and hence beware of this!
5. You can find the internal name using code also.
Ex: string internalName = item.Fields["Field Display Name"].InternalName;
Here in the below link you will see a list of Content types in SharePoint and the Internal Name for it:
Please free to comment and share this post, if this helps you!

Jun 4, 2012

Creating and Deploying Custom Web Part in SharePoint

In this article, we will learn how to create a Custom Web Part in SharePoint using Visual Studio.
After reading this article, you will learn the following:
  Ø  Creating custom web part using visual studio
  Ø  How to use Labels, Rich text box and Buttons (with events) and validation   
        controls in the custom web part?
  Ø  How to validate the fields in custom web part in SharePoint?
  Ø  How to deploy the web part in SharePoint site?

Scenario:
Suppose that in a SharePoint page, you want the users to comment about the page or send some feedback, and then you can use this web part.

Solution:
It is created the following solution using Visual Studio 2005.
Steps:
1. Open the Visual Studio -> Click File -> New project -> Select Visual C# from Project types -> SharePoint -> web Part (Use this link for downloading the Visual Studio Extensions for SharePoint for creating SharePoint solutions in the Visual Studio 2005)
2. Once created, delete the web part present in the solution named webpart1. Now click on the Project Solution -> Add -> New Item -> SharePoint -> Web Part -> Give the name as CommentWebPart -> Click Add to create a web part file in the project solution
3. Now, we will create controls and add in the web part. See the following code which is used for creating this web part.
Program.cs:
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace CommentWebPart
{
    [Guid("745a216c-1126-4000-a189-02ebc60d7e67")]
    public class CommentWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
        TextBox txtContactName;
        TextBox txtEmailAddress;
        InputFormTextBox txtBox;
        Button btnSubmit;
        Button btnCancel;
        Label lblSpace;

                                     
        public CommentWebPart()
        {
            
        }

        protected override void CreateChildControls()
        {
            try
            {
                base.CreateChildControls();

                Table t;
                TableRow tr;
                TableCell tc;

                // Creating a table to add the controls in it
                t = new Table();

                // Label for contact name
                tr = new TableRow();
                tc = new TableCell();
                tc.Style["padding-top"] = "5px";
                tc.VerticalAlign = VerticalAlign.Top;
                Label lblConatctName = new Label();
                lblConatctName.Text = "Conact Name";
                tc.Controls.Add(lblConatctName);
                tr.Controls.Add(tc);


                // Text box for contact name
                tc = new TableCell();
                tc.VerticalAlign = VerticalAlign.Top;
                txtContactName = new TextBox();
                txtContactName.ID = "txtContactName";
                txtContactName.Width = Unit.Pixel(250);
                tc.Controls.Add(txtContactName);

                /* Creating required field validator for Contact Name. 
                * If the value is empty, then should throw error on clicking button Submit*/

                RequiredFieldValidator objName = new RequiredFieldValidator();
                objName.ControlToValidate = "txtContactName";
                objName.ErrorMessage = "Conatct Name cannot be empty";
                tc.Controls.Add(objName);
                tr.Controls.Add(tc);

                t.Controls.Add(tr);
                
                // Label for email id
                tr = new TableRow();
                tc = new TableCell();
                tc.VerticalAlign = VerticalAlign.Top;
                Label lblEmailId = new Label();
                lblEmailId.Text = "Email ID";
                tc.Controls.Add(lblEmailId);
                tr.Controls.Add(tc);

                // Text box for email id
                tc = new TableCell();
                tc.VerticalAlign = VerticalAlign.Top;
                txtEmailAddress = new TextBox();
                txtEmailAddress.ID = "txtEmailAddress";
                txtEmailAddress.Width = Unit.Pixel(250);
                tc.Controls.Add(txtEmailAddress);

                /* Creating required field validator for Email ID. 
                * If the value is empty, then should throw error on clicking button Submit*/

                RequiredFieldValidator objEmailID = new RequiredFieldValidator();
                objEmailID.ControlToValidate = "txtEmailAddress";
                objEmailID.ErrorMessage = "Email Id cannot be left empty";
                tc.Controls.Add(objEmailID);
                tr.Controls.Add(tc);

                /* Creating Regular Expression validator for Email ID. 
                * If the value is empty or not in a regular Email ID format,
                * then should throw error on clicking button Submit*/

                RegularExpressionValidator objEmail = new RegularExpressionValidator();
                objEmail.ControlToValidate = "txtEmailAddress";
                objEmail.ErrorMessage = "Email Id is not in the correct format";
                objEmail.Display = ValidatorDisplay.Dynamic;
                objEmail.ValidationExpression = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-
                Z]\.)+[a-zA-Z]{2,9})$";
                tc.Controls.Add(objEmail);
                tr.Controls.Add(tc);

                t.Controls.Add(tr);

                // Label for text box
                tr = new TableRow();
                tc = new TableCell();
                tc.VerticalAlign = VerticalAlign.Top;
                Label lblComments = new Label();
                lblComments.Text = "Comments";
                tc.Controls.Add(lblComments);
                tr.Controls.Add(tc);
                               
                            
                // Creating a rich text box for comments
                tc=new TableCell();
                tc.VerticalAlign=VerticalAlign.Top;
                txtBox=new InputFormTextBox();
                txtBox.ID="txtBox";
                txtBox.RichText = true;
                txtBox.RichTextMode=SPRichTextMode.FullHtml;
                txtBox.TextMode=TextBoxMode.MultiLine;
                txtBox.Rows=10;
                txtBox.Width=Unit.Percentage(100);
                txtBox.Height = Unit.Percentage(30);
                tc.Controls.Add(txtBox);
                tr.Controls.Add(tc);

                t.Controls.Add(tr);

                // Creating empty cell for spacing
                tr = new TableRow();
                tc = new TableCell();
                lblSpace = new Label();
                lblSpace.Text = "   ";
                tc.Controls.Add(lblSpace);
                tr.Controls.Add(tc);

                tc = new TableCell();

                // Creating button submit event
                btnSubmit = new Button();
                btnSubmit.ID = "btnSubmit";
                btnSubmit.Text = "Submit";
                btnSubmit.Click +=new EventHandler(btnSubmit_Click);
                tc.Controls.Add(btnSubmit);
                
                // Creating button cancel event
                btnCancel = new Button();
                btnCancel.ID = "btnCancel";
                btnCancel.Text = "Cancel";
                btnCancel.Click +=new EventHandler(btnCancel_Click);
                
                lblSpace = new Label();
                lblSpace.Text = "   ";
                tc.Controls.Add(lblSpace);
                tr.Controls.Add(tc);
                tc.Controls.Add(btnCancel);
                
                tr.Controls.Add(tc);

                t.Controls.Add(tr);

                this.Controls.Add(t);

            }
            catch (Exception ex)
            {
                string err = "Error Occured while loading the web part" + ex.Message;
            }
      }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                // Creating the EMail message 
                System.Text.StringBuilder txtMessage = new System.Text.StringBuilder();
                txtMessage.Append("Contact Name: ");
                txtMessage.AppendLine(txtContactName.Text);
                txtMessage.Append("Email Address: ");
                txtMessage.AppendLine(txtEmailAddress.Text);
                txtMessage.AppendLine();
                txtMessage.AppendLine("Comment:");
                txtMessage.AppendLine(txtBox.Text);

                // Creating the Email subject message
                System.Text.StringBuilder txtsubject = new System.Text.StringBuilder();
                txtsubject.Append("Comment from");
                txtsubject.Append(txtContactName.Text);

                // Cerating the message header
                System.Collections.Specialized.StringDictionary txtmessageHeader = new
                System.Collections.Specialized.StringDictionary();
                
                // To whom the mail should be sent
                txtmessageHeader.Add("to", "MAIL ID OF THE USER TO WHOM THE COMMENT HAS TO BE SENT");

                // From whom the comment is being sent
                txtmessageHeader.Add("from", txtEmailAddress.Text);
                txtmessageHeader.Add("subject", txtsubject.ToString());
                txtmessageHeader.Add("content-type", "text/RichText");

                // Send the email with the comment from the user
                Microsoft.SharePoint.Utilities.SPUtility.SendEmail(SPContext.Current.Web, txtmessageHeader,               
                txtMessage.ToString());

                // Clear the fields after sending the mail
                txtContactName.Text = "";
                txtEmailAddress.Text = "";
                txtBox.Text = "";
                
            }
            catch (Exception ex)
            {
                string str= "Unable to send mail:" + ex.Message;
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            // Clear the fields on clicking cancel
            txtContactName.Text = "";
            txtEmailAddress.Text = "";
            txtBox.Text = "";
        }

   }
}
4. Build the web part and check for errors.
5. Now, to deploy the solution Right Click on the project solution -> Select Deploy to add the solutions in the Solution Gallery.

6. Now the solution will be present in the Solution Gallery (Central Administration-> Operations -> Solution Management) in the SharePoint site and we have to add it to our site.
7. Go to the SharePoint site -> Site Actions -> Site Settings -> galleries -> web parts

8. Now, Click on New -> You will see the list of deployed web parts and click on Comment Web part and then Click Populate Gallery


9. Now the web part is available in the SharePoint site but we have to add Safe control entry in the web.config of the site. Add the following in the web.config in the SAFE CONTROLS tag section 


10. Now you can add the created custom web part in your SharePoint site. This will look as follows:
According to the required field validation, if the name and email id is field is left empty then the following screen should be seen:
If the Email ID is given in the wrong format then according to the regular expression validation, the following screen should be seen:
If the input fields are correctly given, then you will be able to submit the 
comment to the described mail ID in the code as shown below:
HAPPY SHARING J
Also, to know about the Basics of Visual Web Part read this article.
To know about Creating and Deploying a Visual Web Part using Visual Studio 2010 read this article.
Please free to share your thoughts and share this post if this helps you!

May 23, 2012

Error: The language-neutral solution package was not found.

While using Visual Studio, you may get the following error
“The language-neutral solution package was not found.”
Solution:
There are three ways you can fix this problem:
1. This may be caused due to the CACHING issue in the Visual Studio and hence restarting the Visual Studio will help you in fixing the issue.
2. Sometimes the solution you are trying to update will not get updated properly. Hence delete the following folders (By navigating to In Visual Studio   -> Right click on project in Solution Explorer window -> Select Open folder in Windows Explorer)  bin, obj and package.
After deleting these folders, rebuild and deploy the solution which will work out.
3. Or finally, you can retract the solution from the Central Admin (in case of SharePoint related issues) and then uninstall the solution dll from the assembly folder. Then try to deploy the solution.
Please free to comment and share this post, if this helps you!

May 16, 2012

Chart Controls in ASP.Net

I was looking at creating chart controls for implementing in the .Net web applications. I didn’t like to use the 3rd party tools or any freeware tools. Well, while browsing found a cool feature provided by MICROSOFT for the same.
In this article, we will have a look at the CHART CONTROLS in .Net applications.
Pre-requisites
Ø  Visual Studio 2008 SP1, Link to download
Ø  .NET Framework 3.5 SP1, Link to download
Ø   Microsoft Chart Controls, Link to download
Ø  Visual Studio 2008 Add-on for the Chart Controls, Link to download
Ø  Documentations by Microsoft, Link to download
Ø  Web and Windows Application Samples, Link to download
Types of Charts
Ø  Area Charts
Ø  Bar column Charts
Ø  Circular Charts
Ø  Combination Charts
Ø  Data Distribution Charts
Ø  Error Bar
Ø  Financial Charts
Ø  Line Charts
Ø  Pie Doughnut Charts
Ø  Point Charts
Ø  Price Range Financial Charts
Ø  Pyramid Funnel Charts
Ø  Range Charts
Examples
The examples provided by Microsoft are very clear and easy. Hence you can download and try the samples. Also, the control is easy to use, just drag and drop the control and start using it.
Namespace
The namespace which we use here is System.Web.UI.DataVisualization.Charting.
More about Chart Controls
Ø  This control is not available for Visual Studio 2005.
Ø  It is available as a native component in Microsoft Visual Studio 2008 SP1.  First you have to install the Chart Controls provided by Microsoft and then the add-ons for using the control.
Ø  But in Visual Studio 2010, it is present as inbuilt component. We can just use it!
More Useful Reference Links
Installing and using Chart Controls in Visual Studio 2010, here.
Using Chart Controls in Visual Studio 2005, here.
Happy Sharing!

May 3, 2012

Programmatically get SharePoint Users with Group Name

In this article, we will come to know how to list all the users from the SharePoint site using c#.
Scenario:
We have to retrieve all the Users from the SharePoint site with the Group Name using object model.
Solution:
I have created a console application which will group the users with the Group Name and also display the User details.
Code (.cs):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace UserPermissions_Console
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {                
                    GetUsersGroups();                
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error Occured: " + ex.Message);
            }
        }
        private static void GetUserRoles()
        {
            using (SPSite site = new SPSite("http://sitename"))
            {

                SPWeb web = site.OpenWeb();
                Console.WriteLine("\n\n Roles Assignments:");

                foreach (SPRoleAssignment roleA in web.RoleAssignments)
                {
                    Console.WriteLine("The following Role definition bindings exist for" + roleA.Member.Name);                    
                    foreach (SPRoleDefinition roledef in roleA.RoleDefinitionBindings)
                    {
                        Console.WriteLine(roledef.Name);                    
                    }
                }
                Console.ReadLine();
            }
        }
        private static void GetUsersGroups()
        {   
            using (SPSite site = new SPSite("http://sitename"))
            {

                SPWeb web = site.OpenWeb();
                SPGroupCollection groupCollection = web.SiteGroups;
                
                foreach (SPGroup group in groupCollection)
                {
                    SPUserCollection userCollection = group.Users;
                    Console.WriteLine("Group Name :" + group.Name+"\n");
                    
                    foreach (SPUser user in userCollection)
                    {
                        Console.WriteLine("User Name: " + user.Name + " Email: " + user.Email + " Login: " + user.LoginName);
                    }
                }
                //Iterate the owners group
                SPGroup ownerGroup = web.AssociatedOwnerGroup;                
                foreach (SPUser ownerUser in ownerGroup.Users)
                {
                    Console.WriteLine("User Name: " + ownerUser.Name + " Email: " + ownerUser.Email + " Login: " + ownerUser.LoginName);
                }
            }
            Console.ReadLine();
        }

    }
}
You can download the full solution using this link.
See Also
Check if current user is member of a SharePoint group using JQuery
Hope this helps you! Please free to comment and share this post.

May 1, 2012

RegisterForEventValidation can only be called during Render()

To know about creating a Grid view with Paging and Exporting the view to Word and Excel documents read this article.
The following is the screen shot which you get due to this error:


This error occurs whenever we are trying to render control to response. To fix this problem I have added EnableEventValidation="false" to @Page directive of aspx page.
This will look like as follows:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" EnableEventValidation="false" %>
This code will fix this issue.

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server

To know about creating a Grid view with Paging and Exporting the view to Word and Excel documents read this article.
The following is the screen shot which you get due to this error:


This error occurs whenever you are trying to export the grid view data to excel or word. This occurs due to the reason that the compiler thinks that the control is not added in the form. Hence to resolve this issue, add the overriding function in the code
public override void VerifyRenderingInServerForm(Control control)
{
  /* Verifies that the control is rendered */
}

This code will fix this issue.

Grid View with Paging into Excel and Word in ASP.Net

After reading this article, you will come to know the following:
   1.   Using grid view control in the ASP.Net applications
   2.   Creating and connecting the SQL database in the ASP.Net applications
   3.   Creating PAGING in the grid view
   4.   Tabbed navigation in the ASP.Net application with single GRIDVIEW
   5.   Converting the grid view with paging to WORD and EXCEL document

Scenario:
   1.   We have to use grid view to display the details from the SQL database
   2.   We have to use single grid view control to display details from two different tables from the database
   3.   We have to enable PAGING in the grid view control
   4.   We have to convert the details displayed in the grid view to word and excel document

Solution:
   1.   I have created an ASP.Net Web application using Microsoft Visual Studio 2005.   
   2.   I have placed two buttons (as tabbed navigation) for displaying the details from two different tables in two tabs.
   3.   Also, you will find the solution for paging in the grid view control.
   4.  Then, after displaying the details, we can convert the details to word and excel document.
    
Code (.cs file):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
public partial class _Default : System.Web.UI.Page
{ 
    String strDetails = String.Empty;
    SqlConnection conn = new SqlConnection("Data Source=ServerName;Initial 
    Catalog=Database Name;Integrated Security=True");
    protected void Page_Load(object sender, EventArgs e)
   {
        if (!IsPostBack)
        {
            BindData(strDetails);
        }       
        GridView1.PageIndexChanging += new GridViewPageEventHandler(GridView1_PageIndexChanging);
    }        
    protected void btn1_Display_Click(object sender, EventArgs e)
    {
        strDetails = "";
        GridView1.PageIndex = 0;
        BindData(strDetails);
    }
    protected void btn2_Dipslay_Click(object sender, EventArgs e)
    {
        strDetails = "UserGroup";
        GridView1.PageIndex = 0;
        BindData(strDetails);
    }    
    protected void btn_ExportExcel_Click(object sender, EventArgs e)
   {              
        Response.Clear();
        Response.AddHeader("content-disposition","attachment;filename=FileName.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite =new HtmlTextWriter(stringWrite);
        //turn off paging before exporting the details
        GridView1.AllowPaging = false;
        strDetails = ViewState["strDetailsValue"].ToString();
        BindData(strDetails);
        GridView1.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
        //turn the paging on again after writing the values to the excel document
        GridView1.AllowPaging = true;
        BindData(strDetails);
        Response.Flush();
   }
    protected void btn_ExportWord_Click(object sender, EventArgs e)
   {
        Response.Clear();
        Response.AddHeader("content-disposition", attachment;filename=FileName.doc");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-word ";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        //turn off paging before exporting the details
        GridView1.AllowPaging = false;
        strDetails = ViewState["strDetailsValue"].ToString();
        BindData(strDetails);
        GridView1.RenderControl(hw);
        Response.Write(sw.ToString());
        Response.End();
        //turn the paging on again after writing the values to the excel document
        GridView1.AllowPaging = true;
        BindData(strDetails);
        Response.Flush();        
    }
    private void BindData(String strDetails)
    {
        DataSet ds = new DataSet();
        conn.Open();
        SqlCommand cmd;
        if (strDetails == "UserGroup")
        {
            cmd = new SqlCommand("Select * from table1", conn);
        }
        else
        {
            cmd = new SqlCommand("Select * from table2", conn);
        }
        SqlDataAdapter sqlAd = new SqlDataAdapter(cmd);
        sqlAd.Fill(ds);
        GridView1.Controls.Clear();
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
        GridView1.Visible = true;
        ViewState.Add("strDetailsValue", strDetails);
        conn.Close();     
    }
   //Handling the paging event in the grid view control 
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        strDetails = ViewState["strDetailsValue"].ToString();
        BindData(strDetails);
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
      /* Verifies that the control is rendered */
    }
  }
Hope this helps you! Please free to comment and share this post.
If you are getting the following error:
RegisterForEventValidation can only be called during Render();
Read this article to fix the error.
If you are getting the following error:
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
Read this article to fix the issue.