Tuesday, February 16, 2010

How to Loop through GridView Rows Asp.net C#




Please visit my new Web Site WWW.Codedisplay.com



This is a small tips for asp.net C# vb.net novice developers. We can loop through GridView rows using two ways:

1. Use GridViewRow class to loop through or navigate the GridView rows from outsite the GridView control's event.

2. Use general for loop based on GridView Rowcount method.

In this article i will generate the following interface:
Loop gridview rows

Loop through GridView rows using GridViewRow class:
protected void cmdGridViewRow_Click(object sender, EventArgs e)
    {
        string str = "";
        foreach (GridViewRow oItem in GridView1.Rows)
            str = str + oItem.Cells[0].Text + " -- " + oItem.Cells[1].Text + " -- " + oItem.Cells[2].Text + "
";
        ltrlText.Text = str;
    }
Loop through GridView rows using simple For loop:
protected void cmdRowCount_Click(object sender, EventArgs e)
    {
        string str = "";
        for (int i = 0; i < GridView1.Rows.Count; i++)
            str = str + GridView1.Rows[i].Cells[0].Text + " -- " + GridView1.Rows[i].Cells[1].Text + " -- " + GridView1.Rows[i].Cells[2].Text + "
";
            ltrlText.Text = str;
    }
To generate the example the complete HTML markup code is:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="gridview_loop.aspx.cs" Inherits="gridview_loop" %>

<!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>How to loop through gridview rows</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" Width="800px" AutoGenerateColumns="False" >
         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
             <asp:BoundField DataField="Brand Name" HeaderText="Brand Name" />
             <asp:BoundField DataField="Category Name" HeaderText="Category Name" />
             <asp:BoundField DataField="Product Name" HeaderText="Product Name" />
         </Columns>
        </asp:GridView>
        <br />
        <hr />
        <asp:Button runat="server" ID="cmdGridViewRow" Text="Loop GridViewRow" OnClick="cmdGridViewRow_Click" />
        <asp:Button runat="server" ID="cmdRowCount" Text="Loop Row Count" OnClick="cmdRowCount_Click" />
        <br />
        <hr />
        <br />
        <asp:Literal runat="server" ID="ltrlText"></asp:Literal>
    </div>
    </form>
</body>
</html>
The complete server side code is:
using System;
using System.Web.UI.WebControls;

public partial class gridview_loop : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = clsDBUtility.GetDataTable("SELECT B.Name [Brand Name],C.Name [Category Name], " +
                    "P.Name [Product Name] FROM " +
                    "Brand B, Category C, Product P " +
                    "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3");
            GridView1.DataBind();
        }
    }
    protected void cmdGridViewRow_Click(object sender, EventArgs e)
    {
        string str = "";
        foreach (GridViewRow oItem in GridView1.Rows)
            str = str + oItem.Cells[0].Text + " -- " + oItem.Cells[1].Text + " -- " + oItem.Cells[2].Text + "
";
        ltrlText.Text = str;
    }
    protected void cmdRowCount_Click(object sender, EventArgs e)
    {
        string str = "";
        for (int i = 0; i < GridView1.Rows.Count; i++)
            str = str + GridView1.Rows[i].Cells[0].Text + " -- " + GridView1.Rows[i].Cells[1].Text + " -- " + GridView1.Rows[i].Cells[2].Text + "<br />";
            ltrlText.Text = str;
    }
}
Hope now you can loop through all the rows within a gridview.

10 comments:

Anonymous said...

I was having an issue accessing the info in my rows, but individually calling the cells did the trick, you solved my issue.

Anonymous said...

I am trying to create a master-detail data entry page in asp.net. I am having some difficulty and would like to know if you can help. What I want to do is to have;
1. two textboxes and one combo to select from (this will be saved in the master table)
2. a grid to enter separate rows of data from the user (this will be saved in the details table which is related to the master table in 1 above)

I tried using the gridview control but that is limited as it doesn't allow inserting of records. Is there any help you can give at all as to how to go about this.

Ashish Tomar (Software Developer) said...

Nice Article Bro !!

Anonymous said...

Very good article, it's showing clearly steps by steps to access Gridview. Easy to follow

Anonymous said...

Why do you insist on using that ridiculous pale grey for your code samples? You can only see it properly if you either have bionic eyes or (more realistically) you copy the code into VS or Notepad etc. Couldn't you just make life easier for your readers and make it a colour you can actually see?

Anonymous said...

Oops, please ignore previous comment re code in grey - for some reason my browser hadn't rendered it ptroperly... my apologies.
Thanks for the article, it helped me out.

Anonymous said...

Hi,
I have gridview with no DataBound template. Only ItemTemplate with no controls.
Getting empty values with your method.
Can you please correct me?

Regards
Sneha

Saion Roy said...

Let me know how you bind data and also provide gridview markup.

Zeeshan Arif said...

thanks dear, it was so helpful

Anonymous said...

What about pages, man?

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash