简体   繁体   中英

Not able to select multiple rows with Ctrl Key pressed. Described my approach below

I have a weird 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';
    }
    else
    {
         document.getElementById('<%= CtrlKeyPressed.ClientID %>').value = 'N';
    }
}

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

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

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. (Basically I want to select multiple rows on pressing Ctrl Key)

When I hold the Ctrl key down, then when I click for the first time in gridview row, the value of hidden field comes as 'Y' but when selecting second row, the hidden field value is coming as 'N' (I am expecting to come as 'Y' since Ctrl key is pressed)?

Can anyone please help to solve this issue?

Thanks!!!

It is probably your post back resetting the value of the curKey variable. You should remove this variable and instead inspect the value of the hidden field each time.

Try this:

function setCtrlIsDown(keyCode, isDown) {
    //Check if control key is pressed or not.
    if (keyCode != 17) {
        return;
    }

    document.getElementById('<%= CtrlKeyPressed.ClientID %>').value = isDown ? 'Y' : 'N';
}

<body onkeyup="setCtrlIsDown(event.keyCode, false);" onkeydown="setCtrlIsDown(event.keyCode, true);">

In RowDataBound :-

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

This way the variable won't be reset on post-back, as it will be persisted in ViewState as well as being altered as necessary by the client side JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM