Monday 12 December 2011

Create Column of Sum

Hello reader;

Add Sum Field

First we should have a datatable whose structure should be like this;

ColName           Datatype
StudId                 int
StudName          varchar(50)
Sub1Marks        int
Sub2Marks        int


Student NameSub1 MarksSub2 Marks
testUpdate 98 85
Farah 98 65
Asma 98 92
Ovais 87 85
Tahir 89 98




To create a column at existed datatable we require to add a column using Add Method after creating that column as;




DataColumn DCol= new DataColumn("Sum",typeOf(int));

typeOf(int) , it indicate the column's data type will be integer.

now we have to use the Add method of datatable as;

datatbleName.Columns.Add(DCol);

Add method add the columns in the datable column collection.
.
As we know the sum field should not be stored in database b/c is headach and consume resources. We have a scenerio where we store the marks of subjects in datatable of databse then retrieve it but at run time we require Sum as another field in grid view to accomplish this we require to update every row value of that column.


for (int i=0 ; i<=datablName.rows.Count-1;i++)
{

DT.Rows[i]["Sum"] = Convert.ToInt32(DT.Rows[i]["Sub1Marks"]) + Convert.ToInt32(DT.Rows[i]["Sub2Marks"]);

or using the Index of Column We can set/get the values;


DT.Rows[i][4] = Convert.ToInt32(DT.Rows[i][2]) + Convert.ToInt32(DT.Rows[i][3]);}


then bind this datable with gridview by using datasource method to provide the source and databind method to perform necessory step of mapping and binding.


GridVwName.DataSouce=DT;
GridVewName.DataBind();

I've used SQLSever as backEnd Db ,


To download the Code +Sample db Kindly Follow the link;
http://www.mediafire.com/?n22w1wrnsf822ll

-----------------------------------------------------------------------------------------