13 August 2010

GridView JavaScripts

GridView Control - Javascripts
While working with Grid View I had to write few small JavaScript snippets to perform certain tasks like reading values form one text box in the grid View and assign to a hidden filed so that we can access the same in server side for any changes if user made. Looks simple but I am sharing some of the JavaScript’s which I wrote for Grid View on asp.net page.Read the text box placed in a Grid View and assigns the values to the hidden field. The script is wired to submit button click on client side: 
function SubmitSaveClick() {   
//get reference of GridView control
    var grid = document.getElementById("");
    //variable to contain the cell of the grid
    var cell;
    if (null != grid) {
        if (grid.rows.length > 0) {
            //loop starts from 1. rows[0] points to the header.
            for (i = 1; i < grid.rows.length; i++) {
                //get the reference of first column
                cell = grid.rows[i].cells[2];
                //loop according to the number of childNodes in the cell
                for (j = 0; j < cell.childNodes.length; j++) {
                    //if childNode type is text
                    if (cell.childNodes[j].type == "text") {
                        cell.children[3].value = cell.children[0].value;
                    }
                }
            }
        }
    }
    return true;
}
try
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DateTime dtConvert;
        string dateFormat = string.Empty;
        CheckBox chkGender = e.Row.Cells[1].FindControl("chkGender") as CheckBox;
        chkGender.Attributes.Add("onclick", "ChangeDate();");
        if (chkGender.Checked)
            e.Row.Enabled = true;
}
catch (Exception ex)
{
   LogException(ex);
}
Likewise for adding any events associated with a grid View control for example if you have a check box on the grid and if you want to attach a JavaScript associated with each control on the grid please add following code in the server side on Grid View row data bound.

No comments: