简体   繁体   中英

How to get selected row index of ASP.NET DataGrid Control in JavaScript Method?

There is a DataGrid used in Default.aspx and Requirement is to get the text of all columns of selected row in a javascript method to copy it to clipboard. Currently, I'm doing this task but it selects all the rows of Grid and Past all data to Clipboard.

Default.aspx (Sample File)

<asp:GridView ID="ObjList" runat="server" OnLoad="xyz" AutoGenerateColumns="false" OnRowDataBound="ObjList_RowDataBound" AutoGenerateSelectButton="false"> 
<Columns>
  .
  .
  .
</Columns>

Sample Button which calls javascript method to copy data to clipboard.

<asp:ImageButton ID="BtnCopyToClipboard" ToolTip="Copy To Clipboard"   ImageUrl="img/tlb_list_copy.gif" OnClientClick="CopyGridView('ObjList'); return false;" runat="server" />

Sample JavaScript Function:

function CopyGridView(gridId) {
var div = document.getElementById(gridId);

var sSelectedRowText = div.Rows[iPL_SelectedRowIndex].Value;
if (div != null) {
    div.contentEditable = 'true';
    var controlRange;
    if (document.body.createControlRange) {
        controlRange = document.body.createControlRange();
        controlRange.addElement(div);
        controlRange.execCommand('Copy');
        alert(InfoMsgClipboard);
    }
    div.contentEditable = 'false';
}
}

Any suggestion, how to identify selected row in grid and only copy selected row data in clipboard.

function setSelectedRowId(RowId){
        document.getElementById("txtRowId").value = RowId; }

    private void ObjList_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
    {
       if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.SelectedItem)
       {
          e.Item.Attributes.Add("onclick", "setSelectedRowId('" + e.Item.Cells[0].Text + "');
       }

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