arjun
arjun

Reputation: 17

<asp.HiddenField> value coming as empty in codebehind even after value is set in javascript

Here's my problem. I have a hidden field whose value I change through a javascript method. The value of hiddenfield is set whenever a row is selected in a gridview with ctrl key pressed.

This is how value for hidden field is assigned (Javascript Code):

var curKey;
function checkKey()
{
    //Check if contrl key is pressed or not.
    if (curKey == 17)
    {                
         document.getElementById('<%= CtrlKeyPressed.ClientID %>').value = 'Y';
    }
}

In the code, I have called this javasxcript inside gridview_rowdatabound function which would be like given below :

 gridview.Rows[i].Attributes.Add("onclick",ClientScript.GetPostBackEventReference(grvKanban, "Select$" + i) + ";checkKey()");

In the body of .aspx page, code is something like this (if control key is pressed while clicking any row in gridview, the value of curKey will be 17):

<body onkeyup = "curKey = null;" onkeydown = "curKey=event.keyCode;">

For the hidden field, Code is :

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

Basically I want to know whether Ctrl Key is pressed while selecting the gridview row, which I thought of finding with value of Hidden field. But in code behind, when I try to get the value of CtrlKeyPressed.Value is coming as empty string.

Can anyone please help to solve this issue?

Thanks!!!

Upvotes: 1

Views: 999

Answers (1)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

You need to run checkKey() before the post back. So change this:

gridview.Rows[i].Attributes.Add("onclick",
    ClientScript.GetPostBackEventReference(grvKanban, "Select$" + i) +
    ";checkKey()");

to this:

gridview.Rows[i].Attributes.Add("onclick",
    "checkKey();" +
    ClientScript.GetPostBackEventReference(grvKanban, "Select$" + i));

Upvotes: 1

Related Questions