How to calculate discount price at runtime binding on gridview in ASP.Net c#?

How to calculate discount price at runtime binding on gridview in ASP.Net c#?, someone asked me to explain?

In this article we will discuss, How to calculate discount price at runtime binding on gridview using Read() method, which returns true there are rows to read. If there are no more rows to read then it will return false. We will calculating 15% discounted price for the product.

 We will be using ProductDetail table

Step 1: Create a table using the following script with data:

CREATE TABLEProductDetail 
 ProductId int identity primary key,
 ProductName nvarchar(50),
 UnitPrice int
INSERT INTOProductDetail VALUES('Lenova',523)
INSERT INTOProductDetail VALUES('Nokia 520',550)
INSERT INTOProductDetail VALUES('Micromax',560)
INSERT INTOProductDetail VALUES('Samsung Galaxy S5',926)
INSERT INTOProductDetail VALUES('Sony',450)

Step 2: Copy and paste the following code.


<table style="border: 1px solid #e2e2e2; font-family: Arial">
            <td style="padding:10px 5px 5px 40px">
                <asp:GridView ID="GridView1" runat="server" ></asp:GridView>


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : Page
    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            string ConnString = ConfigurationManager.ConnectionStrings["ShoppingZone"].ConnectionString;
            using (SqlConnection connection = new SqlConnection(ConnString))
                SqlCommand cmd = new SqlCommand("Select * from ProductDetail", connection);
                using (SqlDataReader reader = cmd.ExecuteReader())
                   // Create theDataTable and columns. This will
                   // be used as thedatasource for the GridView
                   DataTable datatable = new DataTable();
                   while (reader.Read())
                       //Calculate the15% discounted price
                       decimal OriginalPrice = Convert.ToInt32(reader["UnitPrice"]);
                       decimal discount = OriginalPrice / 15;
                       decimal DiscountedPrice = OriginalPrice -discount;
                       // Populatedatatable column values from the SqlDataReader
                       DataRow datarow = datatable.NewRow();
                       datarow["ID"] = reader["ProductId"];
                       datarow["Name"] = reader["ProductName"];
                       datarow["Price"] = OriginalPrice;
                       datarow["DiscountedPrice"] = string.Format("{0:0.00}", DiscountedPrice);
                       //Add the DataRowto the DataTable
                   GridView1.DataSource = datatable;


calculate discount price at runtime binding on gridview

Post your comments / questions