Add ID to GridView Row

How to add ID lines to GridView (identifiers should be displayed)?

I am using .NET (C #). I have a GridView control.

I have some javascript functions that control the rows of a table, but for these rows you must have identifiers:

<table> <tr id=1> ... <tr id=2> ... //id should come from database .. 

My GridView is generated from Data from DataBase. It is important not to have a FAKE ROW IDS, but to actually output rows from the database (there is a javascript ajax function that updates the database based on these identifiers and user table manipulations).

Part of my gridview is as follows:

  <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 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 it does not display this identifier.

So how to visualize identifiers from the database for rows in a GridView?

+4
source share
3 answers

Try the 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(); } } 
+14
source

The easiest way is to use a hidden field, access to which you can get from the client and from the server.

 <Columns> <asp:TemplateField > <ItemTemplate> <asp:HiddenField ID="HiddenID" runat="server" Value='<%#Eval("ID") %>' /> </ItemTemplate> </asp:TemplateField> .... </Columns> 
+1
source

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 
0
source

Source: https://habr.com/ru/post/1440493/


All Articles