Link to home
Start Free TrialLog in
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

ASKER CERTIFIED SOLUTION
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
Avatar of kaforad
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>


      
      

      


Thanks for sharing that information !