renathy
renathy

Reputation: 5355

Add ID to GridView Row

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

Answers (4)

Hasan Zafari
Hasan Zafari

Reputation: 385

Make sure that:

  1. You are calling your database Binding function out side the IsPOstback event.

  2. You have not mentioned your RowDatabound Event Signature in Grid Definition

Upvotes: 0

Ali
Ali

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

Tim Schmelter
Tim Schmelter

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

Amol Kolekar
Amol Kolekar

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

Related Questions