Wednesday, November 9, 2011

Displaying ASPxGridView row index number

You can achieve this through two way:
Method 1
Step 1. Add ASPxGridView on your page:

<dx:ASPxGridView ID="grvTest" AutoGenerateColumns="False" runat="server"
DataSourceID="SqlDataSource1" onhtmlrowprepared="grvTest_HtmlRowPrepared"
onhtmlrowcreated="grvTest_HtmlRowCreated">
<Columns>
<dx:GridViewDataTextColumn Caption="RowID" Name="colRowID" VisibleIndex="0"
Width="20px">
<DataItemTemplate>
<dx:ASPxLabel ID="lblRowID" runat="server" Text="lablel">
</dx:ASPxLabel>
</DataItemTemplate>
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="User Name" FieldName="UserName"
Name="colUserName" VisibleIndex="1" Width="100px">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Password" FieldName="Password"
Name="colPassword" VisibleIndex="2" Width="30px">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Role" FieldName="Role" Name="colRole"
VisibleIndex="3" Width="30px">
</dx:GridViewDataTextColumn>
</Columns>
</dx:ASPxGridView>

Step 2: Add following ASPxGridView Event code snippet to your code – behind file (.cs)

protected void grvTest_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
{
if (e.RowType != GridViewRowType.Data) return;

ASPxLabel label = grvTest.FindRowCellTemplateControl(e.VisibleIndex, null, "lblRowID") as ASPxLabel;
label.Text = (e.VisibleIndex + 1).ToString();
}

Method 2
The another way to do it is this one in the Columns section of your GridView control:

<dx:ASPxGridView ID="grvTest" AutoGenerateColumns="False" runat="server"
DataSourceID="SqlDataSource1" >
<Columns>
<dx:GridViewDataTextColumn Caption="RowID" Name="colRowID" VisibleIndex="0"
Width="20px">
<DataItemTemplate>
<dx:ASPxLabel ID="lblRowID" runat="server" Text='<%# Container.ItemIndex + 1 %>'>
</dx:ASPxLabel>
</DataItemTemplate>
</dx:GridViewDataTextColumn>

3 comments :

  1. What if i want to access this and display it in a regular asp label on the same page? How do I access the row index?

    ReplyDelete
  2. I posted a question earlier, and soon after, I figured it out myself. Here is the solution for displaying the row count in a asp label on a page;

    protected void ASPxGvRegistrants_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
    {
    if (e.RowType != GridViewRowType.Data) return;

    ASPxLabel label = ASPxGvRegistrants.FindRowCellTemplateControl(e.VisibleIndex, null,
    "lblRowID") as ASPxLabel;
    label.Text = (e.VisibleIndex + 1).ToString();
    int counter = Convert.ToInt16(txtAttendees.Text) - Convert.ToInt16(label.Text);
    if (Convert.ToInt16(label.Text) >= Convert.ToInt16(txtAttendees.Text))
    {
    lblCounter.Text = "There are NO MORE spots left for this training session.";
    }
    else

    lblCounter.Text = "There are " + counter + " spots left for this training.";
    }

    ReplyDelete
  3. thanks Mark for posting the answer here as well for your DevExpress Grid question...

    ReplyDelete