How to access gridview cell values on client side
|
|
|
|
|
Downloads
If you are seeing this section and do not see download links, this means that you are not logged into our site. If you already are a member, click on the login link
and login into site and come back to this page for downloading the control files. If you are not a member, click on registration link to
become a Winista member and download the control for free.
In this article I will be discussing how you can use client side javascript to access values in specified row and column
of GridView control without doing any post back. I have discussed in my previous articles about highlighting rows and
raising click event in selected row of grid view control, ref to How to highlight gridview row when row is selected and
How to raise gridview server side event
The technique to access cell values will build upon the technique that we used for highlighting rows and raising server side
event. You can refer to same code from those articles to see how client side onclick event was handled for each selected row.
Javascript code in those examples did not deal with cell values. But there are cases when you need to check what values you have in various
cells of the grid view and make decision on client side. For example if a user enters a data in some cell but you need to validate it
against value in some other cell or combination of cells, you may have been doing a post back and then doing the checks and failing user
attempt if something was wrong with the data. But by using this technique you can avoid the post back.
Client Side Javascript
<script language="javascript" type="text/javascript">
var gridViewCtlId = '<%=ctlGridView.ClientID%>';
var gridViewCtl = null;
var curSelRow = null;
var curRowIdx = -1;
function getGridViewControl()
{
if (null == gridViewCtl)
{
gridViewCtl = document.getElementById(gridViewCtlId);
}
}
function onGridViewRowSelected(rowIdx)
{
var selRow = getSelectedRow(rowIdx);
if (null != selRow)
{
curSelRow = selRow;
var cellValue = getCellValue(rowIdx, 0);
alert(cellValue);
}
}
function getSelectedRow(rowIdx)
{
return getGridRow(rowIdx);
}
function getGridRow(rowIdx)
{
getGridViewControl();
if (null != gridViewCtl)
{
return gridViewCtl.rows[rowIdx];
}
return null;
}
function getGridColumn(rowIdx, colIdx)
{
var gridRow = getGridRow(rowIdx);
if (null != gridRow)
{
return gridRow.cells[colIdx];
}
return null;
}
function getCellValue(rowIdx, colIdx)
{
var gridCell = getGridColumn(rowIdx, colIdx);
if (null != gridCell)
{
return gridCell.innerText;
}
return null;
}
</script>
You can download the sample project and play with it to see how this works.
|