Hi nabilabolo,
Refer below code.
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Quantity" HeaderText="Quantity" />
<asp:BoundField DataField="Cost" HeaderText="Cost" />
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button Text="Calculate" runat="server" OnClick="OnCalculate" />
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.AddRange(new System.Data.DataColumn[]
{
new System.Data.DataColumn("Quantity"),
new System.Data.DataColumn("Cost")
});
dt.Rows.Add(30, 5);
dt.Rows.Add(100, 21);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void OnCalculate(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
decimal quantity = Convert.ToDecimal(row.Cells[0].Text);
decimal cost = Convert.ToDecimal(row.Cells[1].Text);
(row.FindControl("lblTotal") as Label).Text = Math.Round(((cost / quantity) * 100), 2).ToString();
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dt As Data.DataTable = New Data.DataTable()
dt.Columns.AddRange(New Data.DataColumn() {
New Data.DataColumn("Quantity"),
New Data.DataColumn("Cost")})
dt.Rows.Add(30, 5)
dt.Rows.Add(100, 21)
GridView1.DataSource = dt
GridView1.DataBind()
End If
End Sub
Protected Sub OnCalculate(ByVal sender As Object, ByVal e As EventArgs)
For Each row As GridViewRow In GridView1.Rows
Dim quantity As Decimal = Convert.ToDecimal(row.Cells(0).Text)
Dim cost As Decimal = Convert.ToDecimal(row.Cells(1).Text)
TryCast(row.FindControl("lblTotal"), Label).Text = Math.Round(((cost / quantity) * 100), 2).ToString()
Next
End Sub
Output
Quantity Cost Total
30 5 16.66
100 21 21.00