Tuesday, 31 January 2012

AutoNumber Column or Auto Number in GridView or DataList ASP.NET

Several times we need to display Auto Number or serial number for displaying records in gridview or other similar controls in ASp.NET.

We can add AutoNumber column by using Container.DataItemIndex property in html markup of the Gridview.

Here's the sample html markup for the page
<title>Auto Number Cloumn in GridView </title>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" 
              AllowPaging="True" AutoGenerateColumns="False"
              DataSourceID="SqlDataSource1" PageSize="6" 
              AlternatingRowStyle-ForeColor="#FFFFFF" >
    <asp:TemplateField HeaderText="Serial Number">
        <%# Container.DataItemIndex + 1 %>
    <asp:BoundField DataField="Name" HeaderText="Name" 
                    SortExpression="Name" />
    <asp:BoundField DataField="Location" HeaderText="Location" 
                    SortExpression="Location" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Name], [Location] FROM [Details]">

Running Total In Gridview Footer in ASP.NET C# VB.NET

In this example i am going to demonstrate how to display running total in footer row or footer template of GridView in ASP.NET using C# and VB.NET. This method works with paging enabled gridview as well.

For demo purpose gridview is populated using sqldatasource having table with columns ID ,Name,Amount

I m showing total of amount column is gridview footer. for this we need to sum the the column in RowDataBound Even of Gridiew

Html source of gridview is
<asp:GridView ID="GridView1" runat="server" 
              DataKeyNames="ID" DataSourceID="SqlDataSource1" 
              ShowFooter="True" AllowPaging="True" PageSize="5" 
              BackColor="#ffffff" BorderColor="AliceBlue" 
              BorderStyle="None" BorderWidth="1px" 
              CellSpacing="2" FooterStyle-BackColor="#da821e" 
     <asp:BoundField DataField="ID" HeaderText="ID" 
                     InsertVisible="False" ReadOnly="True"
                     SortExpression="ID" />
     <asp:BoundField DataField="Name" HeaderText="Name" 
                     InsertVisible="False" ReadOnly="True"
                     SortExpression="Name" FooterText="Total"/>
     <asp:TemplateField HeaderText="Amount">
     <asp:Label ID="lblAmount" runat="server" 
                Text='<%# "$"+Eval("Amount").ToString()%>'>
     <asp:Label ID="lblTotal" runat="server"></asp:Label>
     <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
     <HeaderStyle BackColor="#da821e" Font-Bold="True" 
                  ForeColor="White" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Amount] FROM [Expenses]">
Now we need to write code for summing the column in RowdataBound Even of GridView

C# code behind
01public partial class _Default : System.Web.UI.Page
03    decimal grdTotal = 0;
04    protected void Page_Load(object sender, EventArgs e)
05    {
07    }
08protected void GridView1_RowDataBound
09                   (object sender, GridViewRowEventArgs e)
11 if (e.Row.RowType == DataControlRowType.DataRow)
12 {
13  decimal rowTotal = Convert.ToDecimal
14              (DataBinder.Eval(e.Row.DataItem, "Amount"));
15  grdTotal = grdTotal + rowTotal;
16 }
17 if (e.Row.RowType == DataControlRowType.Footer)
18 {
19  Label lbl = (Label)e.Row.FindControl("lblTotal");
20  lbl.Text = grdTotal.ToString("c");
21 }

VB.NET code behind
01Public Partial Class _Default
02    Inherits System.Web.UI.Page
03    Private grdTotal As Decimal = 0
04    Protected Sub Page_Load
05    (ByVal sender As Object, ByVal e As EventArgs)
07End Sub
09Protected Sub GridView1_RowDataBound
10(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
12If e.Row.RowType = DataControlRowType.DataRow Then
13Dim rowTotal As Decimal =
14Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"))
15grdTotal = grdTotal + rowTotal
16End If
18If e.Row.RowType = DataControlRowType.Footer Then
19Dim lbl As Label = DirectCast(e.Row.FindControl
20                           ("lblTotal"), Label)
21lbl.Text = grdTotal.ToString("c")
22End If
23End Sub
24End Class

Hope this helps

Merge GridView Cells Or Columns in Row ASP.NET C# VB.NET

In this example i am going to describe how to merge GridView cells or Columns in gridview rows containing same data or content using C# and VB.NET in ASP.NET

For this i m using DataBound Event of gridview, counting total rows and then checking each cells value against value of same cell in previous row and then setting the RowSpan of cells.

For this i have created a table containing Counties ,states and respective cities and country and state cells / columns are merged in rows having same country or states.

For knowing how to merge Gridview headers read article below
Merging GridView Header Columns or multiple Headers

You would also like to read
Hide GridView Columns In Normal Mode and Visible In Edit

Running Total In Gridview Footer in ASP.NET C# VB.NET

Html source of the page look like this
<asp:GridView ID="GridView1" runat="server" 
    BorderStyle="None" BorderWidth="1px" CellPadding="4" 
    GridLines="Horizontal" ForeColor="Black" 
    Height="119px" DataSourceID="SqlDataSource1" 
            <asp:BoundField DataField="Country" 
                            SortExpression="Country" />
            <asp:BoundField DataField="State" 
                            SortExpression="State" />
            <asp:BoundField DataField="City" 
                            SortExpression="City" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Country], [State], [City] 
               FROM [Details] ORDER BY [State]">

C# code behind
01protected void GridView1_DataBound1(object sender, EventArgs e)
03  for (int rowIndex = GridView1.Rows.Count - 2;
04                                     rowIndex >= 0; rowIndex--)
05  {
06    GridViewRow gvRow = GridView1.Rows[rowIndex];
07    GridViewRow gvPreviousRow = GridView1.Rows[rowIndex + 1];
08    for (int cellCount = 0; cellCount < gvRow.Cells.Count;
09                                                  cellCount++)
10    {
11     if (gvRow.Cells[cellCount].Text ==
12                            gvPreviousRow.Cells[cellCount].Text)
13     {
14       if (gvPreviousRow.Cells[cellCount].RowSpan < 2)
15       {
16         gvRow.Cells[cellCount].RowSpan = 2;
17       }
18       else
19       {
20        gvRow.Cells[cellCount].RowSpan =
21            gvPreviousRow.Cells[cellCount].RowSpan + 1;
22       }
23       gvPreviousRow.Cells[cellCount].Visible = false;
24    }
25   }
26 }
VB.NET code behind
01Protected Sub GridView1_DataBound1
02           (ByVal sender As Object, ByVal e As EventArgs)
04For rowIndex As Integer = GridView1.Rows.Count - 2 To 0 Step -1
05    Dim gvRow As GridViewRow = GridView1.Rows(rowIndex)
06    Dim gvPreviousRow As GridViewRow = GridView1.Rows(rowIndex + 1)
07    For cellCount As Integer = 0 To gvRow.Cells.Count - 1
08    If gvRow.Cells(cellCount).Text =
09                         gvPreviousRow.Cells(cellCount).Text Then
10    If gvPreviousRow.Cells(cellCount).RowSpan < 2 Then
11    gvRow.Cells(cellCount).RowSpan = 2
12    Else
13    gvRow.Cells(cellCount).RowSpan =
14                       gvPreviousRow.Cells(cellCount).RowSpan + 1
15    End If
16    gvPreviousRow.Cells(cellCount).Visible = False
17    End If
18    Next
19  Next
20End Sub
Download sample code attached

Numeric Number Only TextBox JavaScript RegularExpression Validator

Number only textbox using javascript or regularexpressionvalidator

Numeric or Number Only TextBox Using JavaScript or RegularExpressionValidator.

In this example i am going to decsribe how create Numeric or Number only textbox using javascript or regular expression Validator which accept only numbers in asp.net web page.

1. Number only textbox using javascript.

Go to html source of aspx page and write below mentioned script in head section of page.

1<script type="text/javascript">
2function numberOnlyExample()
4    if ((event.keyCode < 48) || (event.keyCode > 57))
5    return false;

Call this function in onKeyPress event of textbox.
Write this code in html source of textbox.

<asp:TextBox ID="TextBox2" runat="server" 
             onKeyPress="return numberOnlyExample();">

We can also do this programmetically in code behind like this.

on Page_Load event of page add onKeyPress attribute to textbox and call the function to accept only numerics.

1protected void Page_Load(object sender, EventArgs e)
2    {
3       TextBox2.Attributes.Add("onkeypress", "return ((window.event.keyCode >= 48 && window.event.keyCode <= 58))");
4    }
2. Creating Numeric or Number only textbox using Regular Expression Validator. Drag and place RegularExpressionValidator control on aspx page and set it's properties as mentioned below in html code. Set ControlToValidate property to textbox1. Set ValidationExpression. Set ErrorMessage.
HTML Source
     ErrorMessage="Please Enter only Numbers" 
Hope this helps