Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi , i want to declare mathematical expression between values from datatable , for example: i have two columns named 'Variable'(string) and 'Contents' (float) , i have inserted in 'Variables' 3 string a , b and c and in 'Contents' 3 floats are 0, 3 and 6 .Now i want to declare 'a=b+c' in code an when i click on a 'button' the variable a will change in datatable to 9. here is my code but it doesn't work!! help me please !

What I have tried:

C#
private void button11_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from TableVar ";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            DataRow dr1 = dt.Select("Variable='a'").FirstOrDefault();
            DataRow dr2 = dt.Select("Variable='b'").FirstOrDefault();
            DataRow dr3 = dt.Select("Variable='c'").FirstOrDefault();
             
                dr1["Contents"] = Convert.ToDouble(dr2["Contents"])+ Convert.ToDouble(dr3["Contents"]);
                con.Close();
        }
Posted
Updated 27-Nov-19 10:30am
Comments
Leo Chapiro 22-Nov-19 10:05am    
Try to debug your code row by row.
foreigh 22-Nov-19 10:09am    
but i have 3 drows how can i do that ?
#realJSOP 22-Nov-19 10:26am    
with the debugger.
foreigh 22-Nov-19 10:34am    
can you please show me how for example i'm newb ! please
#realJSOP 22-Nov-19 10:48am    
google "how to use visual studio debugger". It's highly likely you'll find a video on youtube.

1 solution

You can achieve that using 2 methods:
1) DataTable.Compute(String, String) Method (System.Data) | Microsoft Docs[^]

C#
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]
	{
		new DataColumn("Variable", typeof(string)),
		new DataColumn("Contents", typeof(int))
	});
dt.Rows.Add(new object[]{"a", 0});
dt.Rows.Add(new object[]{"b", 3});
dt.Rows.Add(new object[]{"c", 6});

var sumObject = dt.Compute("Sum(Contents)", "Variable IN ('a', 'b', 'c')");
//returns: 9


2) Enumerable.Sum Method (System.Linq) | Microsoft Docs[^]

C#
string[] tofind = {"a", "b", "c"};
var result = dt.AsEnumerable()
	.Where(x => tofind.Any(y=> (x.Field<string>("Variable").Equals(y))))
	.Sum(x=>x.Field<int>("Contents"));
//returns: 9


You might be interested in reading this excellent article: A Calculation Engine for .NET[^]
 
Share this answer
 
v2
Comments
CPallini 28-Nov-19 3:00am    
5.
Maciej Los 28-Nov-19 3:13am    
Thank you, Carlo.

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