GridView Tips and Tricks using ASP.NET 2.0

Posted by: Suprotim Agarwal , on 2/7/2008, in Category ASP.NET
Views: 742812
Abstract: In this article, we will explore some of the most frequently asked questions about the GridView control. The article discusses ten tips and tricks that you can use while using the GridView control.
GridView Tips and Tricks using ASP.NET 2.0
 
The GridView control is quiet a handy control and is the most commonly used control when building an ASP.NET site. The more you work with it, the more you realize how powerful it can be while presenting data. In this article, we will explore some of the most frequently asked questions about the GridView control. The article discusses ten tips and tricks that you can use while using the GridView control.

 

Update: The second and third part  of this article containing 17  more tips and tricks about the GridView can be found over here:
 
Tip 1: Add, Update, Delete Records in a Gridview using SqlDataSource
By default, the GridView control doesn’t have support for inserting new records. However you can use the built-in edit or delete functionality of the GridView control. Let us explore how to insert new records and Update and Delete existing records in Gridview. Just copy and paste the code in your project. We will be using the ‘Categories’ table in the ‘Northwind’ database.
GridView.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView.aspx.cs" Inherits="GridView" %>
 
<!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>Grid View Add Update Delete</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"
            DataSourceID="SqlDataSource1" ShowFooter="true" AllowPaging="True" AllowSorting="True" OnRowCommand="GridView1_RowCommand">
            <Columns>
           
                <asp:CommandField ShowDeleteButton="True" ShowEditButton="True"/>               
                <asp:TemplateField HeaderText="CategoryID" InsertVisible="False" SortExpression="CategoryID">
                    <EditItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("CategoryID") %>'></asp:Label>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("CategoryID") %>'></asp:Label>
                    </ItemTemplate>                  
                </asp:TemplateField>
                <asp:TemplateField HeaderText="CategoryName" SortExpression="CategoryName">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CategoryName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("CategoryName") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="CategoryNameTextBox" Runat="server"></asp:TextBox>
                        </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Description" SortExpression="Description">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="DescriptionTextBox" Runat="server"></asp:TextBox>
                    </FooterTemplate>                 
                </asp:TemplateField>
                <asp:templatefield>                  
                        <footertemplate>
                              <asp:linkbutton id="btnNew" runat="server" commandname="New" text="New" />
                        </footertemplate>
                  </asp:templatefield>
               
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=SUPROTIM;Initial Catalog=Northwind;Integrated Security=True"
            DeleteCommand="DELETE FROM [Categories] WHERE [CategoryID] = @CategoryID" InsertCommand="INSERT INTO [Categories] ([CategoryName], [Description]) VALUES (@CategoryName, @Description)"
            ProviderName="System.Data.SqlClient" SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]"
            UpdateCommand="UPDATE [Categories] SET [CategoryName] = @CategoryName, [Description] = @Description WHERE [CategoryID] = @CategoryID">
            <DeleteParameters>
                <asp:Parameter Name="CategoryID" Type="Int32" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="CategoryName" Type="String" />
                <asp:Parameter Name="Description" Type="String" />
                <asp:Parameter Name="CategoryID" Type="Int32" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="CategoryName" Type="String" />
                <asp:Parameter Name="Description" Type="String" />
            </InsertParameters>
        </asp:SqlDataSource>
   
    </div>
    </form>
</body>
</html>
 
GridView.aspx.cs
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        SqlConnection conn = new SqlConnection(
                    ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
        try
        {
            if (e.CommandName.Equals("New"))
            {
                LinkButton btnNew = e.CommandSource as LinkButton;
                GridViewRow row = btnNew.NamingContainer as GridViewRow;
                if (row == null)
                {
                    return;
                }
                TextBox txtCatName = row.FindControl("CategoryNameTextBox") as TextBox;
                TextBox txtDescription = row.FindControl("DescriptionTextBox") as TextBox;               
                SqlCommand cmd = new SqlCommand(
                    "INSERT INTO [Categories] ([CategoryName], [Description]) VALUES (@CategoryName, @Description)",
                    conn);
                cmd.Parameters.AddWithValue("CategoryName", txtCatName.Text);
                cmd.Parameters.AddWithValue("Description",txtDescription.Text);
                conn.Open();
                if (cmd.ExecuteNonQuery() == 1)
                {
                    GridView1.DataBind();
                }
            }
        }
        catch (Exception ex)
        {
 
        }
        finally
        {
            conn.Close();
        }
    }
Web.config
<connectionStrings>
            <addname="NorthwindConnectionString"connectionString="Data Source =.;Integrated Security = SSPI; Initial Catalog=Northwind;"/>
           
</connectionStrings>
 
Tip 2: Paging and Sorting a GridView without Refreshing a Page
If you have created a GridView and have bound it to a data source control, you can avoid postback during sorting and paging by setting  ‘EnableSortingAndPagingCallbacks’ property of the GridView to True.
Just remember that when you set the 'EnableSortingAndPagingCallbacks' property to true, you cannot use Template Fields in the GridView.
 
Tip 3: Pop-up a Confirmation box before Deleting a row in GridView
Add a template field and drop a button in it, using which the user will delete the record. In the OnClientClick event, call the confirm() function as mentioned below:
<asp:TemplateField>
      <ItemTemplate>
        <asp:Button ID="btnDel" runat="server" Text="Delete"
            CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete the record?');" />
      </ItemTemplate>
</asp:TemplateField>
 
Tip 4: Display details of the Row selected in the GridView
Assuming you have a button called ‘Select’ in your GridView with CommandName ‘Select’, to find out the row clicked and display the row’s details, use this code:
C#
private void GridView1_RowCommand(Object sender,
GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            int idx = Convert.ToInt32(e.CommandArgument);
            GridViewRow selrow = GridView1.Rows[idx];
            string fstCell  = selrow.Cells[0].Text;
string scndCell = selrow.Cells[1].Text;
// and so on
// Thanks to Mark Rae (MVP) for pointing the typo. Earlier it was Cells[1] and Cells [2]
        }
    }
VB.NET
Private Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
      If e.CommandName = "Select" Then
            Dim idx As Integer = Convert.ToInt32(e.CommandArgument)
            Dim selrow As GridViewRow = GridView1.Rows(idx)
            Dim fstCell As String = selrow.Cells(0).Text
Dim scndCell As String = selrow.Cells(1).Text
' and so on
      End If
End Sub
 
Tip 5: Retrieve Details of the Row being Modified in GridView
C#
void GridView1_RowUpdated(Object sender, GridViewUpdatedEventArgs e)
    {
        // Retrieve the row being edited.
        int index = GridView1.EditIndex;
        GridViewRow row = GridView1.Rows[index];
 
        // Retrieve the value of the first cell
        lblMsg.Text = "Updated record " + row.Cells[1].Text;
    }
VB.NET
Private Sub GridView1_RowUpdated(ByVal sender As Object, ByVal e As GridViewUpdatedEventArgs)
            ' Retrieve the row being edited.
            Dim index As Integer = GridView1.EditIndex
            Dim row As GridViewRow = GridView1.Rows(index)
 
            ' Retrieve the value of the first cell
            lblMsg.Text = "Updated record " & row.Cells(1).Text
 End Sub
 
Tip 6: Retrieve Details of the Row being Deleted in GridView
The ID of the row being deleted must be in the GridView.DataKeyNames collection.
C#
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int ID = (int)GridView1.DataKeys[e.RowIndex].Value;
        // Query the database and get the values based on the ID
    }
VB.NET
Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
        Dim ID As Integer = CInt(GridView1.DataKeys(e.RowIndex).Value)
        ' Query the database and get the values based on the ID
    End Sub
 
Tip 7: Cancelling Update and Delete in a GridView
RowUpdating - Occurs when a row's Update button is clicked, but before the GridView control updates the row.
RowDeleting – Occurs when a row's Delete button is clicked, but before the GridView control deletes the row.
C#
protected void gvDetail_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        e.Cancel = true;
    }
void GridView1_RowDeleting(Object sender, GridViewDeleteEventArgs e)
    {
        // Check for a condition and cancel the delete
        // There should be atleast one row left in the GridView
        if (GridView1.Rows.Count <= 1)
        {
            e.Cancel = true;
        }
    }
VB.NET
Protected Sub gvDetail_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
   e.Cancel = True
End Sub
Private Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
            ' Check for a condition and cancel the delete
            ' There should be atleast one row left in the GridView
            If GridView1.Rows.Count <= 1 Then
                  e.Cancel = True
            End If
End Sub
 
Tip 8: Paging and Sorting in GridView without using Datasource control
Original Code Author: Ryan Olshan
C#
<asp:GridView ID="gridView" OnPageIndexChanging="gridView_PageIndexChanging" 
OnSorting="gridView_Sorting" runat="server" />
private string ConvertSortDirectionToSql(SortDirection sortDireciton)
{
   string newSortDirection = String.Empty;
   switch (sortDirection)
   {
      case SortDirection.Ascending:
         newSortDirection = "ASC";
         break;
      case SortDirection.Descending:
         newSortDirection = "DESC";
         break;
   }
   return newSortDirection
}
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
   gridView.PageIndex = e.NewPageIndex;
   gridView.DataBind();
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
   DataTable dataTable = gridView.DataSource as DataTable;
   if (dataTable != null)
   {
      DataView dataView = new DataView(dataTable);
      dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
      gridView.DataSource = dataView;
      gridView.DataBind();
   }
}
VB.NET
Private Function ConvertSortDirectionToSql(ByVal sortDireciton As SortDirection) As String
   Dim newSortDirection As String = String.Empty
 
   Select Case sortDirection
       Case SortDirection.Ascending
             newSortDirection = "ASC"
 
       Case SortDirection.Descending
             newSortDirection = "DESC"
   End Select
 
   Return newSortDirection
End Function
 
Protected Sub gridView_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
   gridView.PageIndex = e.NewPageIndex
   gridView.DataBind()
End Sub
 
Protected Sub gridView_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
   Dim dataTable As DataTable = TryCast(gridView.DataSource, DataTable)
 
   If Not dataTable Is Nothing Then
       Dim dataView As DataView = New DataView(dataTable)
       dataView.Sort = e.SortExpression & " " & ConvertSortDirectionToSql(e.SortDirection)
 
       gridView.DataSource = dataView
       gridView.DataBind()
   End If
End Sub
 
Tip 9: Delete Multiple rows in a GridView
Check this article of mine over here.
 
Tip 10: Export GridView To Excel
C#
protected void Button1_Click(object sender, EventArgs e)
    {
        Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
        Response.Charset = String.Empty;
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.RenderControl(hw);
        Response.Write(sw.ToString());
        Response.End();
    }
VB.NET
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
            Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
            Response.Charset = String.Empty
            Response.ContentType = "application/vnd.xls"
            Dim sw As System.IO.StringWriter = New System.IO.StringWriter()
            Dim hw As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(sw)
            GridView1.RenderControl(hw)
            Response.Write(sw.ToString())
            Response.End()
End Sub
 
Well that was a quick overview of some of the most frequently used features of the GridView control. I hope you liked the article and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed or Subscribe Via Email
 

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by murali on Friday, February 8, 2008 11:35 AM
very very good
Comment posted by Milan Mathew on Monday, February 11, 2008 1:05 AM
nice article
Comment posted by Paramesh on Monday, February 11, 2008 1:21 PM
I had tried it this is really good experience to me
Comment posted by sheeba on Saturday, February 16, 2008 5:28 AM
hello

i have one doubt.how to display the value to gridview control without using the database?
Comment posted by sreejith on Sunday, February 17, 2008 12:01 AM
DOUBTS ARE CLEAR BY READING THIS PROGRAM
Comment posted by Melusi Hlwempu on Tuesday, February 19, 2008 5:31 AM
Makes sense.... Thanks.
Comment posted by sanju on Wednesday, February 20, 2008 9:50 AM
i tried but its not working ..how to give page index chaging event??????pls help me
Comment posted by Parthasarathy Mandayam on Friday, February 22, 2008 3:54 PM
If I want to skip the first column while exporting gridview to excel, how can I do that?
Comment posted by avinash on Monday, February 25, 2008 6:09 AM
very nice article!
great!!
keep it up!!
Comment posted by yakoobreddy on Wednesday, February 27, 2008 8:59 PM
very nice article
good experience to me
Comment posted by Sayeed on Thursday, February 28, 2008 9:15 AM
It has really given a good knowledge on GridView
Comment posted by vikki on Friday, February 29, 2008 1:42 AM
xcellent
send code to edit user page in grid view
Comment posted by Tanveer on Friday, February 29, 2008 9:18 AM
Very Nice Articles. i want to know few more like this in datalist, formview and repeater controls
thanks
Comment posted by vvvlad on Saturday, March 22, 2008 9:28 AM
Great article
Thank you
Comment posted by Rasheed on Tuesday, April 1, 2008 7:45 AM
Absolutly Great! i also want to know few more like this in datalist, formview and repeater controls and other controls.
thanks
Comment posted by Asghar Shah on Tuesday, April 1, 2008 2:51 PM
Awsome man great article ..this page is going to my bookmarks for SURE thanks.
Comment posted by sanjay chauhan on Tuesday, April 1, 2008 3:28 PM
Thank for a great article... this is all about any body needs to to with Grid controls in .NET 2.0

Thanks yaaar
Comment posted by Joyish on Wednesday, April 2, 2008 3:39 AM
Nice tips & tricks. Expecting more tricks :)
Comment posted by govardhanaReddy on Wednesday, April 2, 2008 8:47 AM
Yes,i tried it,it is very useful in the realtime scenarios
Comment posted by rafeeq on Wednesday, April 2, 2008 1:06 PM
it is very good article,expecting more on GridView.
Comment posted by Rob on Wednesday, April 2, 2008 1:43 PM
Superbly arranged, thanks!
Comment posted by selvam on Wednesday, April 2, 2008 3:47 PM
Its very good article. Thanks for you!
Comment posted by Md. Tarik Khan on Thursday, April 3, 2008 12:50 AM
This is very good article for basics of gridview. But here It is not given that if we update , delete and add rows of datagrid with use of datatable or dataset, how can we store updated details of datatable or dataset into the database. Please response soon,
Comment posted by Jim on Thursday, April 3, 2008 5:01 AM
Hi Md. The Tip 1 shows that.
Comment posted by henrik on Thursday, April 3, 2008 12:07 PM
I was once studying about how to enhance gridviews and found this link inside the Offciial ASP.NET website
http://asp.net/learn/data-access/
it's really usefull. you can find all the tips given in this article and many others,  and also some things about other controls
Comment posted by henrik on Thursday, April 3, 2008 2:54 PM
I was once studying about how to enhance gridviews and found this link inside the Offciial ASP.NET website
http://asp.net/learn/data-access/
it's really usefull. you can find all the tips given in this article and many others,  and also some things about other controls
Comment posted by Ketki Jai on Friday, April 4, 2008 12:05 PM
Thanks henrik. Nice link.
Comment posted by Tamil. on Monday, April 7, 2008 2:56 AM
Suberb... GREAT ARTICLE!!!!
Comment posted by Lucia on Monday, April 7, 2008 11:48 PM
Really good article for me to teach how to use gridview,Thank you! I sincerely hope you can give same tips and tricks about DataList control.
Comment posted by Bobby :) on Tuesday, April 8, 2008 5:14 AM
Excellent ... Good work ..
Comment posted by Suprotim Agarwal on Tuesday, April 8, 2008 1:29 PM
Thanks everyone for the comments.
Lucia - I will see if I can do the same for DataList.
Comment posted by Lucia on Wednesday, April 9, 2008 8:40 PM
Thank you,expecting...
Comment posted by Taiwo Ojo on Thursday, April 10, 2008 12:44 AM
I really appreciate your effort on this handy article.Thanks a million.lest i forget i will also appreciate if u can provide us article on gridview events in details.Thanks once again.Taiwo From Nigeria.
Comment posted by will smith on Thursday, April 10, 2008 7:03 AM
Nice work and concept
Comment posted by Jay on Friday, April 11, 2008 8:50 AM
When selecting a record from gridview, it renders blank value as "nbsp;", how to avoid it in runtime because my gridview gets values from dataset at runtime.
Comment posted by santosh gudge on Friday, April 18, 2008 4:57 AM
thats an mind blowing ,outstanding article.
keep it up !
Comment posted by lastdonuk on Friday, April 25, 2008 6:38 AM
Excellent article, thanks for sharing
Comment posted by Satheesh on Saturday, April 26, 2008 10:10 AM
Good share! thanks supprotim!
Read more gridview tips here,
http://www.codedigest.com/Articles/ASPNET/70_Useful_GridView_Tips.aspx

Regards,
Satheesh
www.codedigest.com
Comment posted by jyothica on Monday, April 28, 2008 7:12 AM
this is excellent.this is very useful for freshers.i like dis one
Comment posted by Ajay on Tuesday, April 29, 2008 12:50 AM
Got error in GridView.aspx.cs - Expected class, delegate, enum, interface, or struct   GridView.aspx.cs   2   19   
Please help. Don't we have to specify namespace and class in GridView.aspx.cs?
Comment posted by Rahul on Tuesday, April 29, 2008 1:44 PM
Very nice article, I think it's really useful for me .
  Thnaxs
http://hotdesktop.blogspot.com
Comment posted by Suprotim Agarwal on Saturday, May 3, 2008 7:50 AM
Thanks everyone for your comments.

Taiwo: I will try my best.

Ajay: Check that all open braces "{" have a closing "}".
Comment posted by Resh on Wednesday, May 7, 2008 1:44 AM
Nice. Actually i have used Grid_View, but this gives a very good finishing.  
Comment posted by deepa on Thursday, May 8, 2008 3:21 AM
very good article......
Comment posted by Gavin Hendricks on Wednesday, May 14, 2008 2:17 PM
Very good site, thanks for the Tips and Tricks using ASP.NET 2.0. Really Good
Comment posted by amit on Monday, May 19, 2008 7:36 AM
Excellent!
Comment posted by hhh on Thursday, May 22, 2008 2:25 AM
gfgfgfg
Comment posted by shekhar kumar on Thursday, May 22, 2008 7:47 AM
Very good example.
But I need some help.
Is it possible to have two dropdown control insed gridview and there is parenet child relationship.
Means If change the one dropdown item the other should be filled accordingly.
Including all the facility of editing and updating.

thanks
Comment posted by shekhar kumar on Thursday, May 22, 2008 7:48 AM
Very good example.
But I need some help.
Is it possible to have two dropdown control insed gridview and there is parenet child relationship.
Means If change the one dropdown item the other should be filled accordingly.
Including all the facility of editing and updating.

thanks
Comment posted by ps on Thursday, May 22, 2008 7:48 AM
really it helps me a lot.
Comment posted by suprotim agarwal on Thursday, May 22, 2008 11:24 AM
Hi Shekhar: That is certainly possible. I will see if I can find a sample for you.
Comment posted by manikandan on Tuesday, June 3, 2008 2:42 AM
maja
Comment posted by Sushilkumar Pandey on Sunday, June 8, 2008 2:38 AM
Great Article
Comment posted by Amit on Tuesday, June 10, 2008 11:10 AM
very good
Comment posted by dotnetguts on Friday, June 13, 2008 12:32 AM
Check out this DataBinder.Eval() Method  http://dotnetguts.blogspot.com/2006/12/databindereval-method.html  these can ease work without code, simple, easy and fast.
Comment posted by Arun on Friday, June 13, 2008 5:06 AM
great article......... It's helps me a lot.
Comment posted by Nag on Thursday, June 19, 2008 3:36 PM
Good one
Comment posted by Twillers on Tuesday, June 24, 2008 10:54 PM
I have just started working in with forms and Access.   In the first example on this page:   I understand where to put the first part but where do you put the "GridView.aspx.cs"  and the  "Web.config"

Second question:   I am doing the tutorials on "Total Training - Advanced Expressions"  They said to divide the data base into two and put them into " App_Data ".   I am using access to make my data base - How do I divide it into two parts to put into this folder?
Comment posted by Suprotim Agarwal on Wednesday, June 25, 2008 11:01 PM
Twillers: When you were adding a new page, did you select the option of 'Place code in seperate file'? For the web.config, right click your project > Add New item > Web Configuration File.
Comment posted by Pushkar on Friday, June 27, 2008 3:22 AM
Thanks for the Nice Post..
Comment posted by Bharat Jadhav on Friday, June 27, 2008 4:02 PM
Great article!

I would like to add a little note for Tip 10 (Export Gridview to Excel). In order for this to work, one has to override the VerifyRenderingInServerForm() method. Failure to do so returns an error: "Error Control 'ctl00_ContentPlaceHolder1_gdViewExport' of type 'GridView' must be placed inside a form tag with runat=server"

Adding the following piece of code will resolve it:
public override void VerifyRenderingInServerForm(Control control)
{
}
Comment posted by Suprotim Agarwal on Tuesday, July 1, 2008 7:31 AM
Pushkar: Thanks
Bharat: Thanks for the handy tip. I will try it out.
Comment posted by sari on Tuesday, July 8, 2008 12:18 AM
if i want to hide detials of one column except the first one what should i do?
there r 2 fields  name date .when i retrive data through data datagrid i get like this
name       date
--------------
sreejith    6/1/2008   mm/dd/yy format
sreejith     6/2/2008
sreejith     6/3/2008
.
.
.
sreejith     6/30/2008

i want result as

name       date
----------------
sreejith    6/1/2008
            6/2/2008
            6/3/2008
      .
      .
      .
            6/30/2008


could anyone pls give me a solution
Comment posted by Wissam Bishouty on Tuesday, July 22, 2008 2:05 AM
Greetings,
Reply to  sari that asks the question:
if i want to hide detials of one column except the first one what should i do?
there r 2 fields  name date .when i retrive data through data datagrid

i suggest to make datagrid within datagrid,
the first datagrid is for teh names and the embeded datagrid is for the dates and the embeded datagrid can be populated on the itemdatabound event of the outer datagrid.

i hope this will help you.
Regards.
Comment posted by KetkJaipee on Wednesday, July 23, 2008 1:49 AM
Nice suggestion Wissam!!
Comment posted by praveen gupta on Sunday, July 27, 2008 11:25 AM
nice article, it's really work, thank you
Comment posted by shailendra on Wednesday, August 13, 2008 9:17 AM
how we can done the data base deployment
Comment posted by sangam on Friday, August 22, 2008 6:19 AM
Nice article. Perhaps there is still a lot to be discovered about gridview. Thank you. You can find some here:
http://dotnetspidor.blogspot.com
Comment posted by ravi.gandhi on Friday, October 31, 2008 12:28 AM
Nice article and useful comments by all.
Comment posted by madhavi devi on Tuesday, December 2, 2008 2:01 AM
how to bind gridview to microsoft word document
Comment posted by madhavi devi on Tuesday, December 2, 2008 2:03 AM
export gridview to microsoftword document
Comment posted by Mehran on Wednesday, December 24, 2008 4:08 AM
Good Job. I think Paging/Sorting without data source is Dino Esposito's Idea. Now How about hierarchical data something like the third party Grid components. For example Component one.
Comment posted by Farzaneh on Sunday, January 4, 2009 2:08 AM
hello
very very good.
thank you.
Comment posted by H Nasir on Thursday, April 16, 2009 8:21 AM
in footer template the textboxes always shows. how we can hide them unless user presses the "New" button.
actually i want that when user press the "new" button then the textboxes should be enabled to write the text otherwise not. where should i wrote the code for this scenerio. in row_commnand event it is not working well. any suggestions!
Comment posted by Mike J. on Thursday, April 16, 2009 12:19 PM
Could you make a VB.NET version of this article?  I tried converting the C# code to VB but can't get it to work.  I don't know C# much, so I guess that I should learn...
Comment posted by Mike J. on Thursday, April 16, 2009 3:38 PM
Oh, sorry, I was only looking at Tip #1.  I now see that the other tips have VB.  I'm trying to learn how to do updates on a database using a gridview.  Thanks!
Comment posted by sumitra on Friday, May 8, 2009 4:00 AM
this website is helpful for me
Comment posted by adnan pathan on Saturday, May 23, 2009 10:36 AM
if we select any value from dopdownlist or textbox then value search in table and display grid view.
Comment posted by adnan pathan on Saturday, May 23, 2009 10:41 AM
thnks for help
Comment posted by nishant rana on Wednesday, June 3, 2009 3:11 AM
Thanks Harsh for such a wonderful article !
Comment posted by Saquib on Thursday, June 25, 2009 8:49 AM
First of all, great article and thanks for the same. Right now what got me here was, how do I change the Header Text of the GRIDVIEW. I attach the Datasource to the GRIDVIEW, but as the column names are the ones which the table residing in the database has and which is not user friendly, I would like to change them for the ease of the user. Any inputs on it will be of great help.
Comment posted by Suprotim Agarwal on Thursday, July 2, 2009 2:27 AM
Saquib: You did not mention if the columns are autogenerated or not. If they are autogenerated, use alias in your SQL Statement like 'SELECT Name AS [YourName] FROM ...

If not autogenerated, you can use this in teh GridView

<Columns>
<asp:BoundField DataField="name" HeaderText="YourName" />
</Columns>
Comment posted by William Apken on Friday, July 10, 2009 8:18 AM
May be the best column I have come across on the GridView. Thanks. You have saved me a good amount of time on google.
Comment posted by Suprotim Agarwal on Friday, July 17, 2009 2:50 AM
William: Thanks, that was encouraging ;)
Comment posted by mojtaba on Friday, September 25, 2009 2:21 PM
با تشکر چاکر تموم بچه ایرانی یاااااااا
that was GRAET TANX
Comment posted by ashabhatt2707 on Monday, January 25, 2010 12:52 AM
protected void Page_Load(object sender, EventArgs e)
    {
        
        SqlConnection con = new SqlConnection(scon);
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter("select Question,Option1,Option2,Option3,Option4 from QuestionData", con);
      
        da.Fill(ds);
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            

                // myArrayList.Add(dr[0]);
                Questionlable.Text = dr[0].ToString();
                OptionList.Items[0].Text = dr[1].ToString();
                OptionList.Items[1].Text = dr[2].ToString();
                OptionList.Items[2].Text = dr[3].ToString();
                OptionList.Items[3].Text = dr[4].ToString();
                break;
          

        }
}
protected void NextQusButton_Click(object sender, EventArgs e)
    {
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            // myArrayList.Add(dr[0]);
            Questionlable.Text = dr[0].ToString();
            OptionList.Items[0].Text = dr[1].ToString();
            OptionList.Items[1].Text = dr[2].ToString();
            OptionList.Items[2].Text = dr[3].ToString();
            OptionList.Items[3].Text = dr[4].ToString();
            //form1.Controls.Add(Questionlable);
            //form1.Controls.Add(OptionList);
            DataList1.Controls.Add(Questionlable);

        }
}
now i want that when i click on next button then one by one question should be display in the QuestionLable
Thank you
Comment posted by RaviTej on Friday, February 19, 2010 12:35 AM
excellent,superb,great,.... :) ... etc
Comment posted by Majid.ch. on Saturday, March 13, 2010 8:01 AM
TY for F1 .
Comment posted by John on Thursday, May 6, 2010 8:46 AM
Great work. Keep it up! <a href="http://dopyt.crispat.sk/" title=Dopyt">Dopyt</a>
Comment posted by Omar on Saturday, October 30, 2010 2:38 PM
thanks, exciting topics!
I have tried
int index=Convert.ToInt32(e.CommandArgument);
but formatexception error pops up
I am using my own user defined a method called (GetDatabase)to populate the gridview with data from MySql database. and templated gridview e.g gridview is a linkbutton.

Pls help me

thanks in advance
my
Comment posted by om prakash on Wednesday, March 2, 2011 5:12 AM
excellent,super,great...this is the website
Comment posted by om prakash on Wednesday, March 2, 2011 5:14 AM
excellent,super,great...this is the website
Comment posted by om prakash on Wednesday, March 2, 2011 5:15 AM
excellent,super,great...this is the website topics
Comment posted by Zebula on Saturday, July 30, 2011 9:30 PM
Tip # 4 will not work if there is no CommandArgument added to the GridView markup. In fact, that will throw an exception since you can't cast an empty string to an int.

A better way is to use the following:
GridViewRow rw = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
Comment posted by Zebula on Saturday, July 30, 2011 9:47 PM
Tip # 10.
I get this error:
"Control 'MainContent_AwesomeGridView' of type 'GridView' must be placed inside a form tag with runat=server."

I can tell you that this GridView IS inside of a form tag with runat="server" so I'm not sure what it's complaining about, do you ?
Comment posted by Periasamy on Saturday, November 5, 2011 3:48 AM
very nice...
Comment posted by muhammad usman khan on Tuesday, April 17, 2012 12:01 AM
thanx alot dear...great work keep it up..
Comment posted by younis on Wednesday, April 18, 2012 12:45 AM
Tip #4 gives me an error "Input string was not in a correct format"., i did some conversions but was not able to solve the problem
Comment posted by Malik Khawar Abbas on Tuesday, August 28, 2012 4:26 AM
Thanks for this wonder article. very good effort for us once again thanks, and what about my blog....
developerqueries.blogspot.com
Comment posted by mohd asif on Monday, January 28, 2013 6:24 AM
great article thak u very much.....