Click here to Skip to main content
15,907,497 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
C#
DataRow dr = dt.NewRow();
dr["id"] = i;
dr["Name"] = "Name" + i.ToString();
dr["Branch"] = Branches[brnc.Next(0, 3)];
dr["Age"] = ag.Next(17, 22);
dr["SocialMarks"] = marks1.Next(50, 100);
dr["MathsMarks"] = marks2.Next(50, 100);
dr["ScienceMarks"] = marks3.Next(50, 100);
dr["TotalMarks"] = dr["socialmarks"].ToString() + dr["MathsMarks"].ToString() + dr["ScienceMarks"].ToString();
dr["AverageMarks"] =//here totalmarks/3.0..that convert to string 
dt.Rows.Add(dr);
Posted
Comments
Rajesh waran 28-Dec-15 4:28am    
try this,
dr["AverageMarks"] =(float.Parse(dr["TotalMarks"].ToString())/3).ToString();
Member 12185899 28-Dec-15 4:53am    
yeah,Thanks Its working ...Iam getting Problem on Adding Marks ..
Rajesh waran 28-Dec-15 5:00am    
Simple, then use the parse for three columns.
dr["TotalMarks"] = (float.Parse(dr["socialmarks"].ToString()) + float.Parse(dr["MathsMarks"].ToString()) + float.Parse(dr["ScienceMarks"].ToString())).ToString();

1 solution

Don't do that.
Please, stop relying on strings. When you do this:
C#
dr["TotalMarks"] = dr["socialmarks"].ToString() + dr["MathsMarks"].ToString() + dr["ScienceMarks"].ToString();
It performs string concatenation - so if the social marks are 17, the maths maths are 42 and the Science marks are 36, then the total marks will become "174236" - and dividing that by 3 is not going to produce a "reasonable" average! The situation becomes even worse if the marks aren't integers, because you end up trying to divide "17.042.036.0" by three and that makes no sense to anyone!

Instead, store your values in their native format: integers in integer fields, doubles in double columns, dates in DateTime columns, and so forth. That way, the storage all sorts itself out.
C#
int socialMarks = marks1.Next(50, 100);
int mathsMarks = marks2.Next(50, 100);
int scienceMarks = marks3.Next(50, 100);
int totalMarks = socialMarks + mathsMarks + scienceMarks;
dr["SocialMarks"] = socialMarks;
dr["MathsMarks"] = mathsMarks;
dr["ScienceMarks"] = scienceMarks;
dr["TotalMarks"] = totalMarks;
dr["AverageMarks"] = (double) totalmarks / 3.0;
 
Share this answer
 
Comments
Member 12185899 28-Dec-15 5:12am    
Thank You
OriginalGriff 28-Dec-15 5:20am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900