Skip to main content

How To Read GridView Cell value using Javascript

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReadGridView.aspx.cs" Inherits="ReadGridView" %>

<!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>

   <script type="text/javascript"> function Read() {
  var oDataGrid = document.getElementById("<%= GridView1.ClientID %>")
  var tableRows = oDataGrid.rows;
  var rawDataRows = new Array();
  //somewhere to put the actual data
  for (var i = 0; i < tableRows.length; i++) {
     var thisRow = tableRows[i];
     for (var j = 0; j < thisRow.cells.length; j++) {
        alert(oDataGrid.rows(i).cells(j).innerHTML);
        }
     }
  }
   </script>

</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
               <Columns>
                   <asp:BoundField DataField="Item" HeaderText="Item " />
                   <asp:BoundField DataField="Price" HeaderText="Price" />
               </Columns>
           </asp:GridView>
           <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Read();" /></div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 ReadGridView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = _sampleData;
            GridView1.DataBind();
        }
    }
    public DataTable _sampleData
    {
        get
        {
            DataTable dt = (DataTable)Session["DataTable"];
            if (dt == null)
            {
                dt = new DataTable();
                dt.Columns.Add(new DataColumn("ID", typeof(string)));
                dt.Columns.Add(new DataColumn("Item", typeof(string)));
                dt.Columns.Add(new DataColumn("Price", typeof(string)));


                dt.Rows.Add(new object[] { "1", "XX", "12.43", });
                dt.Rows.Add(new object[] { "2", "XX1", "11.43", });
                dt.Rows.Add(new object[] { "3", "XX2", "13.43", });
                Session["DataTable"] = dt;
            }
            return dt;
        }
        set
        {
            Session["DataTable"] = value;
        }
    }
}

Comments

Popular posts from this blog