Reputation: 5355
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?
Upvotes: 9
Views: 19504
Reputation: 385
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
Upvotes: 0
Reputation: 684
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
Upvotes: 0
Reputation: 460108
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>
Upvotes: 2
Reputation: 2325
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();
}
}
Upvotes: 22