How to For Each Loop through GridView Rows Asp.net C# VB.Net

In many purposes we need to loop through GrdiView rows like for manipulation, replacement, padding characters etc. 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.

Objective/Outcome:
How to For Each Loop through GridView Rows Asp.net Csharp VB.Net

To do the Example First Create 2 Database Tables:

CREATE TABLE [dbo].[Brand](
	[ID] [bigint] NOT NULL,
	[Name] [varchar](max) NOT NULL,
 CONSTRAINT [PK_Brand] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[Product](
	[ID] [bigint] NOT NULL,
	[Name] [varchar](max) NULL,
	[Description] [varchar](max) NULL,
	[BrandID] [bigint] NULL,
 CONSTRAINT [PK_Product_2] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Now Insert Some Data:

INSERT INTO Brand Values(1,'Kohinoor')
INSERT INTO Brand Values(2,'Proctor & Gamble')
INSERT INTO Brand Values(3,'Telenor')
INSERT INTO Brand Values(4,'Unilever')

INSERT INTO PRODUCT VALUES(1,'Lux Beauty Soap','Product of Unilever',4)
INSERT INTO PRODUCT VALUES(2,'Tibbet Pomed','Winter Product',1)
INSERT INTO PRODUCT VALUES(3,'Data SIM','Subscriber Identity Module',3)
INSERT INTO PRODUCT VALUES(4,'Nippon','Color Television',1)

Now modify the Web.Config File to Connect to Database:

<configuration>
  <connectionStrings>
    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
    <!--<add name="BONConnection" connectionString="Data Source=XXX.com;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->
  </connectionStrings>
...................
...................

Note: If you use windows authentication then use the first key. Otherwise use second key line. Update server name, Database name, User name, Password as per your settings.

Now add the GridView Control like Below:

<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" 
        AutoGenerateColumns="False" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
         <Columns>
             <asp:BoundField DataField="Name" HeaderText="Name"/>
             <asp:BoundField DataField="Description" HeaderText="Description" />
             <asp:BoundField DataField="Brand" HeaderText="Brand" />
        </Columns>
        </asp:GridView>

        <hr />
        <asp:Button runat="server" ID="cmdGridViewRow" Text="Foreach Loop GridViewRow" OnClick="cmdGridViewRow_Click" />
        <asp:Button runat="server" ID="cmdRowCount" Text="For Loop Row Count" OnClick="cmdRowCount_Click" />
        

        <hr />
        

        <asp:Literal runat="server" ID="ltrlText"></asp:Literal>

Now Bind GridView from Database:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt;
            String SQL = "SELECT P.ID ID, P.Name Name, P.Description Description, B.ID BrandID,B.Name Brand" +
                        " FROM Product P, Brand B" +
                        " WHERE P.BrandID=B.ID";


            string sConstr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(sConstr))
            {
                using (SqlCommand comm = new SqlCommand(SQL, conn))
                {
                    conn.Open();
                    using (SqlDataAdapter da = new SqlDataAdapter(comm))
                    {
                        dt = new DataTable("tbl");
                        da.Fill(dt);
                    }
                }
            }
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim dt As DataTable
            Dim SQL As [String] = "SELECT P.ID ID, P.Name Name, P.Description Description, B.ID BrandID,B.Name Brand" + " FROM Product P, Brand B" + " WHERE P.BrandID=B.ID"


            Dim sConstr As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
            Using conn As New SqlConnection(sConstr)
                Using comm As New SqlCommand(SQL, conn)
                    conn.Open()
                    Using da As New SqlDataAdapter(comm)
                        dt = New DataTable("tbl")
                        da.Fill(dt)
                    End Using
                End Using
            End Using
            GridView1.DataSource = dt
            GridView1.DataBind()
        End If

Now Loop through GridView Rows Using Foreach Loop:
C# Code:

    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 + "<br/>";
        ltrlText.Text = str;
    }

VB.Net Code:

    Protected Sub cmdGridViewRow_Click(sender As Object, e As EventArgs)
        Dim str As String = ""
        For Each oItem As GridViewRow In GridView1.Rows
            str = (str + oItem.Cells(0).Text & Convert.ToString(" -- ")) + oItem.Cells(1).Text + " -- " + oItem.Cells(2).Text + "<br/>"
        Next
        ltrlText.Text = str
    End Sub

Now Loop through GridView Rows Using For Loop:
C# Code:

    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;
    }

VB.Net Code:

    Protected Sub cmdRowCount_Click(sender As Object, e As EventArgs)
        Dim str As String = ""
        For i As Integer = 0 To GridView1.Rows.Count - 1
            str = (str + GridView1.Rows(i).Cells(0).Text & Convert.ToString(" >> ")) + GridView1.Rows(i).Cells(1).Text + " >> " + GridView1.Rows(i).Cells(2).Text + "<br/>"
        Next
        ltrlText.Text = str
    End Sub

Hope now you can loop through all the rows within a GridView.

Download Code Example C#        Download Code Example VB.Net

2 thoughts on “How to For Each Loop through GridView Rows Asp.net C# VB.Net

  • January 12, 2015 at 10:58 am
    Permalink

    Hello! Quick question that’s entirely off topic. Do you know how to make your site – Gaye, mobile friendly? My blog looks weird when browsing from my iphone 4. I’m trying to find a template or plugin that might be able to resolve this issue. If you have any recommendations, please share. With thanks!

    Reply
    • January 13, 2015 at 2:57 am
      Permalink

      You have to implement responsive design. In existing system its a bit tough. But for new applications lot of framework available in market like bootstrap etc. For better understanding communicate with a web designer.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code