-1

I want to get the sum of only two columns for each data row in datable and display it in datagridView. I tried to use link query:

SqlCommand cmd = new SqlCommand("SELECT * FROM Student", con);

DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());

dataGridView1.Rows.Add(dt.Rows.Count);

foreach(DataRow row in dt.Rows)
{
    dataGridView1.CurrentRow.Cells["Column1"].Value = row["FullName"].ToString();
    dataGridView1.CurrentRow.Cells["Column2"].Value = row["Maths"].ToString();
    dataGridView1.CurrentRow.Cells["Column3"].Value = row["Physics"].ToString();                
    dataGridView1.CurrentRow.Cells["Column4"].Value = dt.AsEnumerable().Sum(r => double.Parse(r[1].ToString()) + double.Parse(r[2].ToString()));
}

This code throws this exception:

The format of the input string is incorrect.

Any suggestions?

8
  • 1
    Are you sure its column 1 and column 2? You know that the first column is at index 0? Maybe it would be easier if you would use the string overload, so find the column by it's name instead of the index. Commented Mar 25 at 8:57
  • Yes I'm sure that the indexes are correct Commented Mar 25 at 8:57
  • 3
    "I'm sure to be correct" famous last words :D Commented Mar 25 at 8:58
  • Put a breakpoint on the problematic line. Run to it. When you hit the breakpoint, go to the Immediate Window. Type in ?r[1].ToString(). What is displayed? Type in ?r[2].ToString(). What is displayed? Commented Mar 25 at 8:59
  • Where this r is coming from? What if you change r[1] to row["Maths"] and r[2] to row["Physics"]? Commented Mar 25 at 9:03

3 Answers 3

2

I believe what you want to have is this:

SqlCommand cmd = new SqlCommand("SELECT *, Maths + Physics as MySum FROM Student", con);

DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());

dataGridView1.ItemsSource = dt;
Sign up to request clarification or add additional context in comments.

Comments

2

If you don't want to modify SQL query, you can try adding computable column to the data table:

using var cmd = new SqlCommand("SELECT * FROM Student", con);

using var reader = cmd.ExecuteReader();

DataTable dt = new DataTable();
dt.Load(reader);

dt.Columns.Add("MySum", dt.Columns["Maths"].DataType).Expression = "Maths + Physics";

Comments

0

Your code

dt.AsEnumerable().Sum(r => double.Parse(r[1].ToString()) + double.Parse(r[2].ToString()))

will query the entire DataTable instead of summing the current row, all rows in the column are summed.

2 Comments

How to Sum the current row?
@user3309231 Stare long and hard at row["Physics"].ToString() and see if you can work it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.