How to add ID to GridView rows (IDs should be rendered)?
I am using .NET (C#). I have GridView control.
I have some javascript functions that are manipulating table rows, but it is necessary to have IDs for those rows:
<table>
<tr id=1> ...
<tr id=2> ... //id should come from database
..
My GridView is genereted from Data from DataBase. It is important not to have FAKE ROW IDS, but really row ids from DB (there are some ajax javascript function that updates DB based on those IDs and user manipulations with table).
Part of my GridView is the following:
<asp:GridView ID="grdNews" runat="server" BorderStyle="None" RowStyle-BorderStyle="None"
GridLines="None" CssClass="table" Style="white-space: nowrap" AutoGenerateColumns="False"
DataKeyNames="ID" AllowSorting="True" AllowPaging="true" OnSorting="grdNews_Sorting" OnRowDataBound="grdNews_RowDataBound">
<RowStyle BorderStyle="None" />
<HeaderStyle CssClass="nodrag" />
<Columns>
....
I have tried the following:
protected void grdNews_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.ID = grdNews.DataKeys[e.Row.RowIndex].Value.ToString();
}
}
This gives e.Row.ID the correct value, but this doesn’t render this ID.
So, how to render IDs from DataBase for Rows in 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
Try following….
protected void grdNews_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow row = e.Row;
row.Attributes["id"] =grdNews.DataKeys[e.Row.RowIndex].Value.ToString();
}
}
Method 2
The easiest way would be to use a hidden-field which you can access from client- and from server-side.
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:HiddenField ID="HiddenID" runat="server" Value='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
....
</Columns>
Method 3
Vb.net code
Private Sub gvPayments_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvPayments.RowDataBound
Dim counter As Integer = 0
For Each oItem As GridViewRow In gvPayments.Rows
counter += 1
oItem.Cells(1).Text = counter.ToString()
oItem.Attributes("id") = "tr_" + counter.ToString
Next
End Sub
Method 4
Make sure that:
- You are calling your database Binding function out side the IsPOstback event.
- You have not mentioned your RowDatabound Event Signature in Grid Definition
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