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>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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;
Method 2
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0