Home » C# ProgrammingRSS

Gridview: How to create a column that will autogenerate the serial number of each row

Hi all,

I have a gridview and I want to autopopulate the serial number columns. For eg, the gridview has 10 rows. The user deleted the first row. I want the gridview serial number to automatically shift down by one. Ie., 10-->9, 9-->8 and so on.

Can this be done? Any help is much appreciated!

 

12 Answers Found

 

Answer 1

1. Add OnRowDataBound="GridView1_RowDataBound" inside your GridView declaration:

<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" ...
2. Add TemplateField inside your GridView:
                <asp:TemplateField HeaderText="Serial number">
                    <ItemTemplate>
                        <asp:Label ID="lblSerial" runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
3. Add this in code-behind:
    int i = 1;
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblSerial = (Label)e.Row.FindControl("lblSerial");
            lblSerial.Text = i.ToString();
            i++;
        }
    }

 

Answer 2

If it is just for display, not for changing the serial  number in the database, try a TemplateField column  like this:

VB.NET:

<asp:TemplateField HeaderText="Serial No" >
   <ItemTemplate>   
       <%# CType(Container, GridViewRow).RowIndex + 1%>
   </ItemTemplate>
</asp:TemplateField>

C#:

<asp:TemplateField HeaderText="Serial No" >
   <ItemTemplate>   
       <%# ((GridViewRow)Container).RowIndex + 1%>
   </ItemTemplate>
</asp:TemplateField>

Jos

 

Answer 3

Hi Kipo,

Your solution is perfect. But using templatefield means that i will not be able to use EnablePagingandsortingCallback. Is this a tradeoff or is there any other method? Thks alot.

 

Answer 4

you can use a boundfield:

<Columns>

<asp:CommandFieldButtonType="Image"CancelImageUrl="~/data/commands/cancel.gif"

DeleteImageUrl="~/data/commands/delete.gif"DeleteText="Verwijder"EditImageUrl="~/data/commands/edit.gif"

EditText="Bewerk"SelectImageUrl="~/data/commands/download.gif"SelectText="Download bestand"

ShowDeleteButton="True"ShowEditButton="True"ShowSelectButton="True"UpdateImageUrl="~/data/commands/save.gif"

UpdateText="Opslaan">

<HeaderStyleWidth="10%"/>

</asp:CommandField>

<asp:BoundFieldHeaderText="Nr."ReadOnly="true">

<ItemStyleHorizontalAlign="Right"Width="1%"/>

</asp:BoundField>

 

Then on the codebehing:

protectedvoid gridLidDocument_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType.Equals(DataControlRowType.DataRow))

{

e.Row.Cells[1].Text = "" + ((((GridView)sender).PageIndex * ((GridView)sender).PageSize) + (e.Row.RowIndex + 1));

}

 

Answer 5

You can replace code-behind with this:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblSerial = (Label)e.Row.FindControl("lblSerial");
            lblSerial.Text = ((GridView1.PageIndex * GridView1.PageSize) + e.Row.RowIndex + 1).ToString();
        }
    }

 

Answer 6

Hi tompy nation and Kipo,

the solution is great! Now I can enable call back as well. Now Im able to move on. Ur help  is much appreciated.

 

Answer 7

<asp:GridView  runat="server" id="gridview1">
<Columns>
<asp:TemplateField ItemStyle-Height="20">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView> 

 

Answer 8

 Hi kipo,

 

Can you show me how to achieve this in Code Behind

 

          <asp:TemplateField HeaderText="Serial number">
                    <ItemTemplate>
                        <asp:Label ID="lblSerial" runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>

 

 

Coz I am loading my grid view dynamically based on many conditions..

 

Thank You

 

 

Answer 9

int i=0; 

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

         i+=1;

        label lblSerial = (Label)e.row.findcontrol("lblSerial");

        lblSerial.Text = i.tostring();

      }

}

 

if the gridview  has more pages, change the i value based on PageIndex.

 

Answer 10

 HI

With this,

label lblSerial = (Label)e.row.findcontrol("lblSerial");

 

You are asking me  to find a control of the type Label , that already exits in the Grid.

 

But , I dont declare anything in my ASP code...

This is the source of my Grid, you can see the commented areas to see when I am trying to set my Item Template.PLease help

// ASP Code
 
<asp:GridView ID="grdSearchResults"Width="100%"  CellPadding="8"CellSpacing="0" runat="Server"AutoGenerateColumns="false"PageSize="10"
           
AlternatingRowStyle-CssClass="odd"RowStyle-CssClass="even"HeaderStyle-HorizontalAlign="Left"GridLines="None"AllowSorting="true"
           
OnSorting="grdSearchResults_Sorting"OnRowCreated="grdSearchResults_RowCreated"Visible="false"EnableViewState="true"  >            
           
           
</asp:GridView>
 
// C# Code
 
public void BindDataToSearchResultsGrid(string sortExpression, string sortDirection)
        {
            //Create arrays of search criteria and search values
            ArrayList arrSearchCriteriaID = new ArrayList();
            ArrayList arrSearchValOperator = new ArrayList();
            ArrayList arrTxtSearchValue = new ArrayList();
            ArrayList arrSearchValsForAndOr = new ArrayList();            
            ArrayList arrSearchDetails = new ArrayList();
            InputSearchValueType inputSearchValueType = InputSearchValueType.Text;
 
            int i = 0;
            cntSearch = Convert.ToInt32(ViewState["cntSearch"]);
            foreach (GridViewRow row  in gvSearch.Rows)
            {
                if (row.Visible)
                {
                    TableCell cell = row.Cells[1] as TableCell;
 
                    DropDownList ddlSearchCriteria = (DropDownList)cell.FindControl("ddlSearchCriteria");
                    if (ddlSearchCriteria != null && ddlSearchCriteria.SelectedValue != null)
                        arrSearchCriteriaID.Add(ddlSearchCriteria.SelectedValue);
 
                    DropDownList ddlSearchVals = (DropDownList)cell.FindControl("ddlSearchVals");
                    if (ddlSearchVals != null && ddlSearchVals.SelectedValue != null)
                        arrSearchValOperator.Add(ddlSearchVals.SelectedValue);
 
                    TextBox txtSearchValue = (TextBox)cell.FindControl("txtSearchValue");
                    DropDownList ddlSearchValue = (DropDownList)cell.FindControl("ddlSearchValue");
                    TextBox calSearchValue = (TextBox)cell.FindControl("calSearchValue");
                    if (txtSearchValue != null && txtSearchValue.Visible)
                    {
                        arrTxtSearchValue.Add(txtSearchValue.Text);
                        inputSearchValueType = InputSearchValueType.Text;
                    }
                    else if (ddlSearchValue != null && ddlSearchValue.Visible)
                    {
                        arrTxtSearchValue.Add(ddlSearchValue.SelectedValue);
                        inputSearchValueType = InputSearchValueType.DropDownList;
                    }
                    else if (calSearchValue != null && calSearchValue.Visible)
                    {
                        arrTxtSearchValue.Add(calSearchValue.Text);
                        inputSearchValueType = InputSearchValueType.Calendar;
                    }
 
                    DropDownList ddlSearchValsForAndOr = (DropDownList)cell.FindControl("ddlSearchValsForAndOr");
                    if (ddlSearchValsForAndOr != null && ddlSearchValsForAndOr.SelectedValue != null)
                        arrSearchValsForAndOr.Add(ddlSearchValsForAndOr.SelectedValue);
 
                    arrSearchDetails.Add(new SearchDetails(Convert.ToInt32(arrSearchCriteriaID[i]), arrSearchValOperator[i].ToString(), inputSearchValueType, arrTxtSearchValue[i].ToString(), arrSearchValsForAndOr[i].ToString()));
                    i++;
                }
            }
 
            //Put Search Details into Session variable. It's array of objects.
            Session["arrSearchDetails"] = arrSearchDetails;
 
            //Get Search results by passing array of search criteria and values
            SqlDataReader dataReader = WebSearchService.Current.GetSearchResults(arrSearchCriteriaID, arrSearchValOperator, arrTxtSearchValue, arrSearchValsForAndOr , sortExpression, sortDirection);
 
            //grdSearchResults.Columns.Clear();
            List<OptionsWebSearchColumns> searchColumnsList = WebSearchService.Current.GetSearchColumnsToDisplay(Convert.ToInt32(arrSearchCriteriaID[0]), arrTxtSearchValue[0].ToString()).ToList();
            if (searchColumnsList.Count() > 0)
            {
               
                if (_isMultipleDeleteAllowed)
                {
                    if (grdSearchResults.Columns.Count > 1)
                    {
                        for (int index = grdSearchResults.Columns.Count-1; index >= 1; index--)
                            grdSearchResults.Columns.RemoveAt(index);
                    }
                }
                else
                    grdSearchResults.Columns.Clear();               //Clear all columns
 
                //Get selected View ID from Views dropdown list
                int selectedViewID = Convert.ToInt32(((Site)this.Page.Master).SelectedViewListItem.Value);
 
                foreach (OptionsWebSearchColumns searchColumn in searchColumnsList)
                {
                    //Get the primary table based on WebSearch table. This will be used for deleting multiple rows  from search results.
                    ViewState["PrimaryTable"] = searchColumn.OptionsWebSearch.QueryTable.ToString();
 
                    if (searchColumn.IsLink.GetValueOrDefault())
                    {                        
                        string LinkURL = searchColumn.LinkURL;
                        string paramName = "";
                        if (LinkURL.Contains('?'))      //Querystring parameter is present
                        {
                            string[] arrUrl = LinkURL.Split('?');
                            paramName = arrUrl[1].ToString();
                        }
 
                        HyperLinkField fld = new HyperLinkField();                        
                        fld.DataTextField = searchColumn.ColumnName;
                        fld.DataNavigateUrlFields = new string[] { paramName };
                        fld.DataNavigateUrlFormatString = searchColumn.LinkURL + "=" + "{0}" + "&curViewID=" + selectedViewID;                          
                        fld.HeaderText = searchColumn.ColumnDisplay;
                        if (searchColumn.AllowSort.GetValueOrDefault()) fld.SortExpression = searchColumn.ColumnName;                      
                        fld.HeaderStyle.CssClass = fld.ItemStyle.CssClass = searchColumn.TableClass;
                        if (searchColumn.ColumnWidth != null) fld.HeaderStyle.Width = fld.ItemStyle.Width = new Unit(searchColumn.ColumnWidth.GetValueOrDefault(), UnitType.Percentage);
                        grdSearchResults.Columns.Add(fld);
 
                        grdSearchResults.DataKeyNames = new string[] { paramName };
                    }
                    else
                    {
                        BoundField fld = new BoundField();
                        fld.DataField = searchColumn.ColumnName;                        
                        fld.HeaderText = searchColumn.ColumnDisplay;
                        if (searchColumn.AllowSort.GetValueOrDefault()) fld.SortExpression = searchColumn.ColumnName;                      
                        fld.HeaderStyle.CssClass = fld.ItemStyle.CssClass = searchColumn.TableClass;
                        if (searchColumn.ColumnWidth != null) fld.HeaderStyle.Width =  fld.ItemStyle.Width = new Unit(searchColumn.ColumnWidth.GetValueOrDefault(), UnitType.Percentage);
                        grdSearchResults.Columns.Add(fld);
                    }
 
                    //TemplateField tFld = new TemplateField();
                    //tFld.HeaderText = "Serial #";
                    //tFld.ItemStyle.Width = 10;
                    //tFld.HeaderStyle.Font.Bold = true;
                   
                   
                   
 
                }                
            }
            else
            {
                grdSearchResults.AutoGenerateColumns = true;
            }
 
            grdSearchResults.Visible = true;
            grdSearchResults.DataSource = dataReader;
            grdSearchResults.DataBind();
 
            //Set value for property HasSearchPanelRows on Default page
            ((Default)this.Page).HasSearchPanelRows = dataReader.HasRows;
 
            dataReader.Close();
        }

 

 

Answer 11

Hello everybody

can we use asp:TemplateField and asp:BoundField both in a single grid??

If yes then how to handle deleteCommand on serial  number. mean to say how to write query for that field as it is not any column  of databse..

for e.g--


<Columns>
            <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />
                <asp:TemplateField HeaderText="Serial No">
                    <ItemTemplate>
                        <%# CType(Container, GridViewRow).RowIndex + 1%>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>


<Columns>

            <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />

                <asp:TemplateField HeaderText="Serial No">

                    <ItemTemplate>

                        <%# CType(Container, GridViewRow).RowIndex + 1%>

                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>


<Columns>

                <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False"

                    ReadOnly="True" SortExpression="CategoryID" />

                <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" />

                <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />

            </Columns>


<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NORTHWINDConnectionString %>"

            SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories] WHERE ([CategoryID] &gt;= @CategoryID) ORDER BY [CategoryName]" >

            <SelectParameters>

                <asp:Parameter DefaultValue="10" Name="CategoryID" Type="Int32" />

            </SelectParameters>

        </asp:SqlDataSource>





 

Answer 12

Write this in ItemDataBound of a DridView:

if(e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    Label lblSerial = (Label)e.Item.FindControl("lblSerial");
                    lblSerial.Text =  Convert.ToString(e.Item.ItemIndex + 1);

            }

then

add  this code in a template column of grid or repeaters table data

<asp:Label ID="lblSerial" runat="server"></asp:Label>




 
 
 

<< Previous      Next >>


Microsoft   |   Windows   |   Visual Studio   |   Follow us on Twitter