Wednesday, September 1, 2010

Clientside Validation for Controls inside GridView

Server Side validations for the Controls inside the Gridview will be bit heavy for the pages havingmore than two gridviews. Javascripts can be used to iterate through the controls inside the particular column of grid. We will have to create a Javascript Two dimensional array to hold both the Server ID and Client ID of the control from the GridView PreRender Event. Same can be achieved from GridView RowDataBound Event also.

The following PreRender Event registers a Two Dimensional Array with control's Server ID and Client ID.


protected void GrvPostPromotion_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ClientScriptManager oCsm = this.Page.ClientScript;
            TextBox oGrossSales = e.Row.FindControl("TxtGrossSalesPOP") as TextBox;
            TextBox oNetToGross = e.Row.FindControl("TxtNetToGrossPOP") as TextBox;
            TextBox oSGM = e.Row.FindControl("TxtPSGMPOP") as TextBox;

            oCsm.RegisterArrayDeclaration("TxtGrossSalesPOP", "'" + oGrossSales.ClientID + "'");
            oCsm.RegisterArrayDeclaration("TxtNetToGrossPOP", "'" + oNetToGross.ClientID + "'");
            oCsm.RegisterArrayDeclaration("TxtPSGMPOP", "'" + oSGM.ClientID + "'");                
        }
    }


Your Javascript Validation Function can do the Job like this

function ValidateDraftPostPromoGrid() {
    var rerunThis = false;
    var vFlag = 0;
    var oDisp = document.getElementById('divMessage'); // DIV, where you display the error message
    for (i = 0; i < TxtGrossSalesPOP.length; i++) {
        var oGrossSales = document.getElementById(TxtGrossSalesPOP[i])
        if (oGrossSales.value == "") {
            oGrossSales.className = "txtboxRedBorder";
            oDisp.innerHTML = "Post Promotion Details is Mandatory ";
            vFlag = 1;
            rerunThis = false;
            break;
        }
        else {
            if (isNaN(oGrossSales.value) == false) {
                oGrossSales.className = "txtboxNormal";
                oDisp.innerHTML = "";
                rerunThis = true;
            }
            else {
                oGrossSales.className = "txtboxRedBorder";
                oDisp.innerHTML = "Gross Sales to be entered in numbers ";
                vFlag = 1;
                rerunThis = false;
                break;
            }
        }
    }
return rerunThis;
}

No comments: