ASP.NET - how to get cell value in a gridview using javascript

Asked By chandana
02-Sep-11 02:54 AM
HI..
I need to get cell value in a gridview using javascript (OnclientClick) when i click perticular row cell
how can i do this..
pls help me..
  Vickey F replied to chandana
02-Sep-11 03:00 AM
Follow this code=\


<asp:TemplateField ShowHeader="False">
    <ItemTemplate>
    <asp:HiddenField ID="hdID" runat="server" Value='<%# Eval("JobID") %>' />
    </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="False">
    <ItemTemplate>
    <asp:LinkButton ID="lnkSelect" runat="server" CommandName="select" Text="Select" />
    </ItemTemplate>
</asp:TemplateField>

Then on the OnRowDataBind have code to set the selected row

protected virtual void Grid_RowDataBound(object sender, GridViewRowEventArgs e)

{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
      // Click to highlight row
      Control lnkSelect = e.Row.FindControl("lnkSelect");
      if (lnkSelect != null)
      {
        StringBuilder click = new StringBuilder();
        click.AppendLine(m_View.Page.ClientScript.GetPostBackClientHyperlink(lnkSelect, String.Empty));
        click.AppendLine(String.Format("onGridViewRowSelected('{0}')", e.Row.RowIndex));
        e.Row.Attributes.Add("onclick", click.ToString());
      }
    }        
}

And then in the Javascript I have code like this


<script type="text/javascript">

var selectedRowIndex = null;

function onGridViewRowSelected(rowIndex)

{      
    selectedRowIndex = rowIndex;
}

function editItem()

{   
    if (selectedRowIndex == null) return;

    var gridView = document.getElementById('<%= GridView1.ClientID %>');          
    var cell = gridView.rows[parseInt(selectedRowIndex)+1].cells[0];      
    var hidID = cell.childNodes[0];      
    window.open('JobTypeEdit.aspx?id=' + hidID.value);
}

</script>

Try this and let me know.
  Riley K replied to chandana
02-Sep-11 03:01 AM
Here is the JS function to get the selected value

<script type="text/javascript">
 
var selectedRowIndex = null;
 
function onGridViewRowSelected(rowIndex)
{     
  selectedRowIndex = rowIndex;
}
 
function editItem()
{  
  if (selectedRowIndex == null) return;
 
  var gridView = document.getElementById('<%= GridView1.ClientID %>');         
  var cell = gridView.rows[parseInt(selectedRowIndex)+1].cells[0];     
  var hidID = cell.childNodes[0];     
  window.open('JobTypeEdit.aspx?id=' + hidID.value);
}
 
</script>

on the OnRowDataBind have code to set the selected row

protected virtual void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    // Click to highlight row
    Control lnkSelect = e.Row.FindControl("lnkSelect");
    if (lnkSelect != null)
    {
      StringBuilder click = new StringBuilder();
      click.AppendLine(m_View.Page.ClientScript.GetPostBackClientHyperlink(lnkSelect, String.Empty));
      click.AppendLine(String.Format("onGridViewRowSelected('{0}')", e.Row.RowIndex));
      e.Row.Attributes.Add("onclick", click.ToString());
    }
  }       
}
Create a hidden field in the Grid View like this:
 
<asp:TemplateField ShowHeader="False">
  <ItemTemplate>
    <asp:HiddenField ID="hdID" runat="server" Value='<%# Eval("JobID") %>' />
  </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="False">
  <ItemTemplate>
    <asp:LinkButton ID="lnkSelect" runat="server" CommandName="select" Text="Select" />
  </ItemTemplate>
</asp:TemplateField>

Regards

  aneesa replied to chandana
02-Sep-11 03:04 AM

Getting/Setting value to gridview cells, you need to know the Row Index of Gridview, you can pass row index when you call JS function from gridview

<script language="javascript" type="text/javascript"> 
function update(rowIndexOfGridview) { 
    var ri = rowIndexOfGridview;  
    var grd = document.getElementById('
<%= GridView1.ClientID %>'); 
 
    CellValue = grd.rows[ri].cells[1].childNodes[0].value; // get 
    grd.rows[ri].cells[2].childNodes[0].value = CellValue; assign 
    ........... 
    ............. 
  dipa ahuja replied to chandana
02-Sep-11 03:05 AM
Markup:
<ItemTemplate>
  <asp:LinkButton ID="LnkSelect" CommandName="Select" Text="Select" runat="server" />
</ItemTemplate>
Script:
<script type="text/javascript">
  var selectedRowIndex = null;
  function onGridViewRowSelected(rowIndex) {
    selectedRowIndex = rowIndex;
    alert(rowIndex);
    var gridView = document.getElementById('<%= GridView1.ClientID %>');
    var CellValue = gridView.rows[selectedRowIndex + 2].cells[4].innerText;
  }   
</script>
codeBehind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    LinkButton l = (LinkButton)e.Row.FindControl("lnkSelectRow");
    l.Attributes.Add("onclick""javascript:onGridViewRowSelected(" +
    e.Row.RowIndex + ")");
  }
}
  Reena Jain replied to chandana
02-Sep-11 03:10 AM
hi,

try this and let me know

var theDropdown = grid.rows[i].cells[0].elements[0];   
var selIndex = theDropdown.selectedIndex;
cellPivot = theDropdown.options[selIndex].value;
//or
  
var grid = document.getElementById('<%= GridView1.ClientID %>');
 for(var i=0; i < grid.rows[index].cells.length; i++)
 {
  alert(grid.rows[index].cells[i].innerHTML); //display value of each cell of that row
}
  Anoop S replied to chandana
02-Sep-11 03:59 AM
If you want to get GridView field in client side then use jquery.

follow this steps-

step1. create on css clss in aspx page, like this-

<style type ="text/css" >

.clslbl

{

}

</style>

step2. Assign this css class to control in GridView, like this-

<asp:TemplateField>

<ItemTemplate>

<asp:Label ID="lbl" Text='<%# Eval("field1") %>' runat ="server" CssClass ="clslbl" ></asp:Label>

</ItemTemplate>

</asp:TemplateField>

step3. Now access this control ,like this-

<script type="text/javascript">

function GetValue()
 {
var con = $(".clslbl").value;

}

</script>
.
  James H replied to chandana
02-Sep-11 04:50 AM

Most likely you want

var theDropdown = grid.rows[i].cells[0].elements[0];   
var selIndex = theDropdown.selectedIndex;
cellPivot = theDropdown.options[selIndex].value;

Another possibly easier or more reliable way to do this would be to tag the cells controls you want in some way and select them directly?

  Radhika roy replied to chandana
02-Sep-11 09:57 AM

For that follow these steps-

Photobucket




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

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

<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {
var list = "";
$("#btnGet").click(function() {
$("#<%=GridView1.ClientID %> tr").each(function() {
//Skip first(header) row
if (!this.rowIndex) return;
var age = $(this).find("td:last").html();
list += age + "</br>";

});
$("#listAge").html(list)
});

});
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<input type="button" id="btnGet" value="Get Cell Value" />
<div id="listAge">
</div>
</form>
</body>
</html>



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Create Object of person class
Person personObject = new Person();
//Assign Person list to GridView
GridView1.DataSource = personObject.GetPersonList();
//Call Bindmethod of GridView
GridView1.DataBind();

}
}
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public List<Person> GetPersonList()
{
//Retrun List of Person
List<Person> list = new List<Person>()
{
new Person{ID=1,Name="Person1",Age=32},
new Person{ID=2,Name="Person2",Age=45},
new Person{ID=3,Name="Person3",Age=43},
new Person{ID=4,Name="Person4",Age=21},
new Person{ID=5,Name="Person5",Age=76},
new Person{ID=6,Name="Person6",Age=54},

};

return list;

}

}

 
Hope this will help you.

Create New Account
help
datakey value only. . cant get clicked row of datakey value. . protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType = = DataControlRowType.DataRow) { ImageButton l = (ImageButton)e.Row.FindControl("ImageButton3"); string userid = Gridview1.DataKeys[e.Row.RowIndex you just need to access the DataItem during RowDataBound. Like this: void GridView1_RowDataBound (Object sender, GridViewRowEventArgs e) { / / Check for that the row is a data row & not header or footer if (e.Row.RowType = = DataControlRowType.DataRow) { / / Retrieve the underlying data item. In this example / / the underlying data item is a myRowID" ]; / / . . . do more work . . . } } hi Please try with following code. protected void GridView3_RowDataBound( object sender, GridViewRowEventArgs e) { if (e.Row.RowType = = DataControlRowType.DataRow) { string lsDataKeyValue = GridView3.DataKeys[e.Row.RowIndex].Values[0].ToString(); } } try this way protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e) { if (e.Row.RowType DataControlRowType .DataRow) { object objTemp = GridView1.DataKeys[e.Row.RowIndex].Value as object ; if (objTemp ! = null ) { string
selected line in gridview and for this i have used e.Row.Attributes[ "onclick" ] = ClientScript.GetPostBackClientHyperlink( this .GridView1, "Select$" + e.Row.RowIndex); but this gives an postback and callback argument error You need set the Message like this Please check this e.Row.Attributes[ "onclick" ] = ClientScript.GetPostBackClientHyperlink ( this .GridView1, "Select$" + e.Row.RowIndex); You can use SelectedIndexChanging() event of GridView like this number. Protected Sub GridUsers_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridUsers.RowDataBound Try If IsEditing Then Exit Sub If e.Row.RowType = DataControlRowType.DataRow Then If Convert.ToString(e.Row.Cells(0).ToString()).Trim() <> String.Empty Then 'disable the OnRowDataBind have code to set the selected row protected virtual void Grid_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType = = DataControlRowType.DataRow) { / / Click to highlight row Control lnkSelect = e.Row.FindControl("lnkSelect"); if (lnkSelect ! = null) { StringBuilder click = new StringBuilder(); click.AppendLine(m_View.Page.ClientScript.GetPostBackClientHyperlink(lnkSelect, String.Empty)); click.AppendLine(String.Format("onGridViewRowSelected('{0
runat = "server" CommandName = "select" Text = "Select" / > < / ItemTemplate> < / asp:TemplateField> protected virtual void Grid_RowDataBound( object sender, GridViewRowEventArgs e) { if (e.Row.RowType = = DataControlRowType.DataRow) { / / Click to highlight row Control lnkSelect = e.Row.FindControl( "lnkSelect" ); if (lnkSelect ! = null ) { StringBuilder click = new StringBuilder(); click.AppendLine(m_View.Page.ClientScript.GetPostBackClientHyperlink(lnkSelect, String.Empty)); click.AppendLine(String.Format( "onGridViewRowSelected('{0}')" , e.Row.RowIndex)); e.Row.Attributes abcd" ; dt.Rows.Add(dr); } GridView1.DataSource = dt; GridView1.DataBind(); } } protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e) { if (e.Row.RowType = = DataControlRowType .DataRow) { e.Row.Attributes.Add( "onclick" , "javascript:rowno(" + count + ")" ); count++; } } If the LinkButton is the
to the event in RowDataBound event of gridview as below: protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e) { if (e.Row.RowType = = DataControlRowType.DataRow) { e.Row.Attributes[ " onmouseover" ] = " javascript:setMouseOverColor(this);" ; e.Row.Attributes[ " onmouseout" ] = " javascript:setMouseOutColor(this);" ; e.Row.Attributes[ " onclick" ] = ClientScript.GetPostBackClientHyperlink ( this .GridView1, " Select$" + e.Row.RowIndex); } } Thanks <asp:TemplateField ShowHeader = "False" > <ItemTemplate> <asp:HiddenField ID runat = "server" CommandName = "select" Text = "Select" / > < / ItemTemplate> < / asp:TemplateField> protected virtual void Grid_RowDataBound ( object sender , GridViewRowEventArgs e ) { if ( e . Row . RowType = = DataControlRowType . DataRow ) { / / Click to highlight row Control lnkSelect = e . Row . FindControl ( "lnkSelect" ); if ( lnkSelect ! = null ) { StringBuilder click = new StringBuilder (); click . AppendLine ( m_View . Page . ClientScript . GetPostBackClientHyperlink ( lnkSelect , String . Empty )); click . AppendLine ( String . Format ( "onGridViewRowSelected('{0}')" , e . Row . RowIndex )); e