0

I created a javascript function to get the selected row from a gridview and it is working fine when I use BoundField DataField, but when I use label inside the ItemTemplate in the gridview it returns a value but with html codes.

for example when I use BoundField DataField I get this:

user name 

and when I use label inside ItemTemplate I get this:

<span id="gvCustomers_Label4_6">user name</span>

here is my code:

<script type ="text/javascript" >
    function GetSelectedRow(UserLink) {
        var row = UserLink.parentNode.parentNode;
        var Userid = row.cells[1].innerHTML;
        alert(Userid);
        return false;
    }
</script>

here is the gridview code:

<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="OnPaging">        
    <Columns>
        <asp:TemplateField HeaderText="user name">
            <ItemTemplate>
                <asp:Label ID="Label4" Text='<%#  Eval("user_name")  %>' runat ="server"/>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="ButtonSearch" runat="server" ClientIDMode="Static"  Text='select'  OnClientClick = "return GetSelectedRow(this)" CommandArgument ='<%# Bind("user_name") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
funie200
  • 3,688
  • 5
  • 21
  • 34
arater 2000
  • 143
  • 7
  • Soes this answer your question? [asp:label gets converted as span element](https://stackoverflow.com/questions/34658016/asplabel-gets-converted-as-span-element-when-resource-is-used) - _"If you set the Label.AssociatedControlID value it becomes a label element. **If it is not associated to a control or in other words not being used as a label element it becomes a span element**."_ – stuartd Dec 02 '20 at 16:18

2 Answers2

1

You could do this if you have more than one span or other elements in the cell

row.cells[1].getElementsByTagName("span")[0].innerHTML;
VDWWD
  • 35,079
  • 22
  • 62
  • 79
0

You need to check for a child node and if present, get the value from it.

Something like this:

<script  type ="text/javascript" >
                function GetSelectedRow(UserLink) {
                    var row = UserLink.parentNode.parentNode;
                    var Userid;
                    if(row.cells[1].firstChild) {
                         Userid = row.cells[1].firstChild.innerHTML;
                    } else { 
                         Userid = row.cells[1].innerHTML;
                    }
                    alert(Userid);
                    return false;
                }

      </script>

I have not tested this code but it should give you the idea. Modify it as needed.

This code sample makes some assumptions which could break it so may need to be more robust.

DaveB
  • 9,470
  • 4
  • 39
  • 66