Avatar of kaforad
kaforad
 asked on

Autogeneration Numbers on DataGrid

Hi,

I populate my Datagrid with values from the database by binding fields in the database to the columns in my datagrid.But, I want to polpulate the first column of my dat grid with autogenearated numbers from 1 to number of rows populated by values in database  in my datagrid.

NOTE:I dont want to add any extra autogenerated field to my database table
Can anybody help

Thanks
Dim dv As DataView = GetDataInDatabase         'GetDataInDatabase ,function that select from my DAtabase
                If dv Is Nothing Then
                    dv = New DataView
                End If
                With dgDAtainDaTABASE                 'gDAtainDaTABASE is the id of my datagrid
                  
 
                    .DataSource = dv
                    If dv.Count > 0 Then
                        .PageSize = dv.Count
                    End If
                    .DataBind()
                End With

Open in new window

ASP.NET

Avatar of undefined
Last Comment
Dirk Haest

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Dirk Haest

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Anurag Agarwal

Use ItemDataBound event of the datagrid. In that assign value to your column at run time.
somethig like
private void OnItemDataBound(object sender,
        System.Web.UI.WebControls.DataGridItemEventArgs e)
{
    // Check if the current row contains items; if it's
    // a header or footer row that will throw an error
    if (e.Item.ItemType == ListItemType.Item ||
        e.Item.ItemType == ListItemType.AlternatingItem)
    {
e.Item.Cells[0].Text =i++
     }

}
Initially you can make the value of i as 1 and define it as global var
Anurag
kaforad

ASKER
Thanks  Dhaest and anuragal for attending to me

The line of script by Dhaest must always be added to the text property of the first column of the datagrid.


Another way of writing it could be <%# (Container.itemIndex + 1)%>

 


      
      <asp:TemplateColumn HeaderText="S/No">
    <ItemTemplate>
   <asp:Label ID="lblSerialID" runat="server" Font-Size="8pt" Text='<%# (Container.itemIndex + 1)%>'>
        </asp:Label>
    </ItemTemplate>
    <HeaderStyle  HorizontalAlign="Center" Width="5%" Wrap="False" />
    <ItemStyle HorizontalAlign="Center" />
</asp:TemplateColumn>


      
      

      


Dirk Haest

Thanks for sharing that information !
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23