Friday, 14 August 2015

Get Selected Row Values of a GridView on Client Side using JavaScript

-------------------------------------GRIDPAGE.ASPX--------------------------------------

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
             
            e.Row.Attributes["onclick"] = "GetRowValue(this);"; 
        }


    }

Add a server variable:

<asp:HiddenField ID="hdnSelected" runat="server" />

Add a Style

<style>
        .AquaMarine {
            background-color: red;
        }
    </style>
--------------------------------------GRIDPAGE.ASPX----------------------------------

function GetRowValue(obj) {
            obj.className = 'AquaMarine';
       
            var curRow = parseInt(obj.rowIndex);

            var grid = document.getElementById("<%= GridView1.ClientID %>");

            for (i = 1; i < grid.rows.length; i++) {
                if(i != curRow)
                grid.rows[i].style.backgroundColor = '#ffffff';
            }

            //Initialize hidden filed value
            document.getElementById('<%=hdnRowValues.ClientID%>').value = '';
            //Set values from the row to hidden field.
            for(j=1;j<grid.rows[curRow].cells.length;j++)
            {
             
                cell = grid.rows[curRow].cells[j];
                document.getElementById('<%=hdnRowValues.ClientID%>').value = document.getElementById('<%=hdnRowValues.ClientID%>').value + cell.innerText + ',';
                }
         
              _selectedRowValue = document.getElementById('<%=hdnRowValues.ClientID%>').value;
        }

---------------------------------------------------------------

No comments:

Post a Comment