Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get GridView selected row DataKey in Javascript

I have GridView which I can select a row. I then have a button above the grid called Edit which the user can click to popup a window and edit the selected row. So the button will have Javascript code behind it along the lines of

function editRecord()
{
  var gridView = document.getElementById("<%= GridView.ClientID %>");
  var id = // somehow get the id here ???
  window.open("edit.aspx?id=" + id);
}

The question is how do I retrieve the selected records ID in javascript?

like image 390
Craig Avatar asked Feb 03 '23 13:02

Craig


1 Answers

I worked it out based on JasonS response. What I did was create a hidden field in the Grid View like this:

<asp:TemplateField ShowHeader="False">
    <ItemTemplate>
      <asp:HiddenField ID="hdID" runat="server" Value='<%# Eval("JobID") %>' />
    </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="False">
    <ItemTemplate>
      <asp:LinkButton ID="lnkSelect" runat="server" CommandName="select" Text="Select" />
    </ItemTemplate>
</asp:TemplateField>

Then on the OnRowDataBind have code to set the selected row

protected virtual void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // Click to highlight row
        Control lnkSelect = e.Row.FindControl("lnkSelect");
        if (lnkSelect != null)
        {
            StringBuilder click = new StringBuilder();
            click.AppendLine(m_View.Page.ClientScript.GetPostBackClientHyperlink(lnkSelect, String.Empty));
            click.AppendLine(String.Format("onGridViewRowSelected('{0}')", e.Row.RowIndex));
            e.Row.Attributes.Add("onclick", click.ToString());
        }
    }            
}

And then in the Javascript I have code like this

<script type="text/javascript">

var selectedRowIndex = null;

function onGridViewRowSelected(rowIndex)
{        
    selectedRowIndex = rowIndex;
}

function editItem()
{   
    if (selectedRowIndex == null) return;

    var gridView = document.getElementById('<%= GridView1.ClientID %>');                
    var cell = gridView.rows[parseInt(selectedRowIndex)+1].cells[0];        
    var hidID = cell.childNodes[0];        
    window.open('JobTypeEdit.aspx?id=' + hidID.value);
}

</script> 

Works a treat :-)

like image 97
Craig Avatar answered Feb 16 '23 18:02

Craig