Skip to content Skip to sidebar Skip to footer

Access Hidden Field Within Gridview Control To Set A Value In Javascript?

I've got a gridview with a bunch of template columns. One of those columns is a hidden column that either has a value of 0 or 1. If a row in a grid view is changed I set the valu

Solution 1:

You could add the javascript onchange handler from codebehind:

ProtectedSub GridView1_RowDataBound(ByVal sender AsObject, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow ThenDim hidden = DirectCast(e.Row.FindControl("rowIsChanged"), HtmlInputHidden)
        Dim txtMyDate = DirectCast(e.Row.FindControl("txtMyDate"), TextBox)
        txtMyDate.Attributes("onchange") = "DoSomeValidation(this,'" & hidden.ClientID & "');"EndIfEndSub

C#

protectedvoidGridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow) {
        var hidden = (HtmlInputHidden)e.Row.FindControl("rowIsChanged");
        var txtMyDate = (TextBox)e.Row.FindControl("txtMyDate");
        txtMyDate.Attributes("onchange") = "DoSomeValidation(this,'" + hidden.ClientID + "');";
    }
}

Edit: here is the js-function, it works to set the value and read it after postback:

<scripttype="text/javascript">functionDoSomeValidation(ctrl, hiddenID) {
        var hidden = document.getElementById(hiddenID);
        if(ctrl.defaultValue != ctrl.value)
            hidden.value = "1";
     }
 </script>

Edit2: added an additional check for a difference between the current textbox' value and it's defaultValue.

Post a Comment for "Access Hidden Field Within Gridview Control To Set A Value In Javascript?"