Suppose I have two columns which I am representing with in-memory objects(in reality we can fetch these from database or XML file etc.) These columns are holded by custom type like this:-
public class Test
{
public int TestId1 { get; set; }
public int TestId2 { get; set; }
}Now, what we want in the gridview is that these two columns should be displayed & third column should be generated which will be sum of these two columns.
We can do calculation in Gridview using inline databinding syntax, like this:-
<asp:GridView ID="grdTest" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="ID1" DataField="TestId1" />
<asp:BoundField HeaderText="ID1" DataField="TestId2" />
<asp:TemplateField HeaderText="Result">
<ItemTemplate>
<%# (Convert.ToInt32(Eval("TestId1")) * Convert.ToInt32(Eval("TestId2")))%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>Finally here is the code to bind this gridview:-
private void BindGrid()
{
List<Test> testDate = new List<Test>
{
new Test { TestId1 = 1, TestId2 = 2 },
new Test { TestId1 = 2, TestId2 = 4 },
new Test { TestId1 = 3, TestId2 = 6 }
};
grdTest.DataSource = testDate;
grdTest.DataBind();
}Happy Coding :)
