Menu like Sub-Category Gridview With Javascript Validation and Total Calculation

Gridview Control

— Create Gridview Control as this…

<asp:GridView ID=”gvSubCategoryGrid” runat=”server” ShowFooter=”True” CellPadding=”4″

ForeColor=”#333333″ GridLines=”None” AutoGenerateColumns=”false”>

<RowStyle BackColor=”#E3EAEB” />

<FooterStyle BackColor=”#1C5E55″ Font-Bold=”True” ForeColor=”White” />

<PagerStyle BackColor=”#666666″ ForeColor=”White” HorizontalAlign=”Center” />

<SelectedRowStyle BackColor=”#C5BBAF” Font-Bold=”True” ForeColor=”#333333″ />

<HeaderStyle BackColor=”#1C5E55″ Font-Bold=”True” ForeColor=”White” />

<EditRowStyle BackColor=”#7C6F57″ />

<AlternatingRowStyle BackColor=”White” />

<Columns>

<asp:TemplateField HeaderText=”Product Name”>

<ItemTemplate>

<asp:Label ID=”lblProductName” runat=”server” Text='<%# Eval(“ProductName”) %>’></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText=”Quantity”>

<ItemTemplate>

<asp:TextBox ID=”txtQty” runat=”server” Text='<%# Eval(“Quantity”) %>’ MaxLength=”5″></asp:TextBox>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText=”Unit Price”>

<ItemTemplate>

<asp:TextBox ID=”txtPrice” runat=”server” Text='<%# Eval(“UnitPrice”) %>’ MaxLength=”6″></asp:TextBox>

</ItemTemplate>

<FooterTemplate>

<asp:Label ID=”lblTotal” runat=”server” Text=”Total”></asp:Label>

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText=”Amount”>

<ItemTemplate>

<asp:TextBox ID=”txtAmount” runat=”server” Text='<%# Eval(“Amount”) %>’ ReadOnly=”true”></asp:TextBox>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

Javascript

–Include this script inside head tag..

<script type=”text/javascript” language=”javascript”>
//javascript function to initialize zero in footer  — Call this function in body onload event
function Initialize() {
var grid = document.getElementById(“<%= gvSubCategoryGrid.ClientID %>”);
var gridLength = grid.rows.length;
var FooterTotalArea = grid.rows[gridLength – 1].cells[3]
if (typeof (FooterTotalArea.text) != ‘undefined’)
FooterTotalArea.text = 0
else if (typeof (FooterTotalArea.textContent) != ‘undefined’)
FooterTotalArea.textContent = 0
else if (typeof (FooterTotalArea.innerText) != ‘undefined’)
FooterTotalArea.innerText = 0
}

//javascript function to Validate Quantity
function ValidateQty(Qty, Price, Amount) {
var Quantity = Qty.value;
var patt = /^\d+$/;
var result = patt.test(Quantity);
if (Quantity != parseInt(Quantity)) {
Qty.value = “”
Amount.value = “”
Qty.focus()
alert(“Null Values/String Values/Decimal Values are not allowed..!”);
}
else {
if (result == true) {
Price = document.getElementById(Price)
Price.focus()
}
else {
Qty.value = “”
Qty.focus()
alert(“Negation not allowed..!”);
}
}
}

//javascript function to validate unit price and to find amount and total price
function ValidationAndTotal(Quantity, Price, Amount) {
Quantity = document.getElementById(Quantity)
Price = document.getElementById(Price)
Amount = document.getElementById(Amount)
var FooterTotal = 0;
var UnitPrice = Price.value;
var patt = /^[0-9]{0,6}(\.[0-9]{1,2})?$/;
var result = patt.test(UnitPrice);
if (result == true) {
if (Quantity.value != “”) {
if (Price.value != “”) {
Amount.value = parseFloat(Quantity.value) * parseFloat(Price.value);
var grid = document.getElementById(“<%= gvSubCategoryGrid.ClientID %>”);
var gridLength = grid.rows.length;
for (i = 1; i < gridLength – 1; i++) {
if (grid.rows[i].cells[0].colSpan == 1) {
var TotalPrice = grid.rows[i].cells[3].children[0].value;
if (TotalPrice != “” && isNaN(TotalPrice) == false) {
FooterTotal = parseFloat(FooterTotal) + parseFloat(TotalPrice);
}
}
}
var FooterTotalArea = grid.rows[gridLength – 1].cells[3]
if (typeof (FooterTotalArea.text) != ‘undefined’)
FooterTotalArea.text = FooterTotal
else if (typeof (FooterTotalArea.textContent) != ‘undefined’)
FooterTotalArea.textContent = FooterTotal
else if (typeof (FooterTotalArea.innerText) != ‘undefined’)
FooterTotalArea.innerText = FooterTotal
}
else {
Price.focus()
alert(“Unit Price cannot be empty.. Please enter unit price..!”)
}
}
else {
Quantity.focus()
alert(“Quantity cannot be empty.. Please enter quantity..!”)
}
}
if (result == false) {
Price.value = “”
Amount.value = “”
Price.focus()
alert(“Null Values/String Values/Float Values more than 2 Decimal points are allowed..!”);
}
}
</script>

Asp.Code behind

— VB code to retrieve the information from the table and to formalize based on our requirement…

Code behind page

Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls
Imports SubCategoryGridViewSample.LogicClass
Partial Public Class _Default
Inherits System.Web.UI.Page
Dim objLogicClass As New LogicClass
Dim data As DataTable

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
‘To get Category Name and Product Name
If (Page.IsPostBack = False) Then
Dim lastCategory As String = String.Empty
Dim currentCategory As String = String.Empty
Dim rowCount As Integer = 0
Dim newRow As DataRow
Dim newData As New DataTable
data = objLogicClass.RetrieveProducts()
newData.Columns.Add(“ProductName”)
newData.Columns.Add(“Quantity”)
newData.Columns.Add(“UnitPrice”)
newData.Columns.Add(“Amount”)
For i = 0 To data.Rows.Count – 1
currentCategory = data.Rows(i).Item(0).ToString
If String.Compare(lastCategory, currentCategory) <> 0 Then
newRow = newData.NewRow()
newRow(“ProductName”) = currentCategory
newRow(“Quantity”) = -1
newRow(“UnitPrice”) = -1
newRow(“Amount”) = -1
newData.Rows.Add(newRow)
Else
newRow = newData.NewRow()
newRow(“ProductName”) = data.Rows(i).Item(1).ToString()
newRow(“Quantity”) = 0
newRow(“UnitPrice”) = 0
newRow(“Amount”) = 0
newData.Rows.Add(newRow)
End If
lastCategory = currentCategory
Next
data.Clear()
gvSubCategoryGrid.DataSource = newData
gvSubCategoryGrid.DataBind()
End If
End Sub

Protected Sub gvSubCategoryGrid_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvSubCategoryGrid.RowDataBound

‘ To assign attributes to textbox and to show category name in separate row in grid..
If e.Row.RowType = DataControlRowType.DataRow Then
Dim txtQty As TextBox = CType(e.Row.Cells(1).Controls(1), TextBox)
Dim txtPrice As TextBox = CType(e.Row.Cells(2).Controls(1), TextBox)
Dim txtAmount As TextBox = CType(e.Row.Cells(3).Controls(1), TextBox)
txtQty.Attributes.Add(“onblur”, “ValidateQty(this,'” + txtPrice.ClientID + “‘,'” + txtAmount.ClientID + “‘);”)
txtPrice.Attributes.Add(“onblur”, “ValidationAndTotal(‘” + txtQty.ClientID + “‘,'” + txtPrice.ClientID + “‘,'” + txtAmount.ClientID + “‘);”)
Dim checkQty As String = txtQty.Text
If checkQty = “-1” Then
e.Row.Cells(0).ColumnSpan = 4
e.Row.Cells(0).ForeColor = Drawing.Color.Maroon
e.Row.Cells(0).BackColor = System.Drawing.Color.FromName(“#F8F8FF”)
e.Row.Cells(1).Visible = False
e.Row.Cells(2).Visible = False
e.Row.Cells(3).Visible = False
Else
txtQty.Text = String.Empty
txtPrice.Text = String.Empty
txtAmount.Text = String.Empty
End If
End If
End Sub
End Class

Bussiness Access Layer

Imports SubCategoryGridViewSample.DataAccess
Public Class LogicClass
Dim objDataAccess As New DataAccess
‘To retrieve the Category Name and Product Name
Public Function RetrieveProducts() As DataTable
Return objDataAccess.RetrieveProduct()
End Function
End Class

Data Access Layer

Imports System.Data.SqlClient
Imports System.Data
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Configuration
Imports System.Collections
Imports SubCategoryGridViewSample.LogicClass

Public Class DataAccess
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings(“Constr”).ConnectionString)
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim dt As DataTable
Dim da As SqlDataAdapter

‘To retrieve the Category Name and Product Name
Public Function RetrieveProduct() As DataTable
con.Open()
cmd.Connection = con
cmd.CommandText = “sp_SelectingProducts”
cmd.CommandType = CommandType.StoredProcedure
da = New SqlDataAdapter(cmd)
dt = New DataTable
da.Fill(dt)
dt.Columns.Add(“Qty”)
dt.Columns.Add(“Price”)
Return dt
End Function

End Class

Sql Server

–Table Category
create table tblCategory
(
CategoryId int primary key,
CategoryName varchar(30) unique not null
)

–Table Product
create table tblProduct
(
ProdId int Primary Key,
CategoryId int references tblCategory(CategoryId),
ProdName varchar(30) unique not null
)

–Procedure to retrieve Category Name and Product Name

create procedure sp_SelectingProducts
as
begin
set nocount off
select
c.CategoryName,
p.ProdName
from tblCategory c
join tblProduct p
on c.CategoryId = p.CategoryId
set nocount on
end

Leave a comment

Filed under .Net

Leave a comment