john
john

Reputation: 13

How to add two column value in one final amount?

I have datatable in c#, I want to add two column value in one, Add means 2+2 =4 like that. please help me this my below code not working

for (int i = 0; i < dtOrdersDetail.Rows.Count; i++)
{
  DataRow dtItemRow = dtOrderReceipt.NewRow();
  dtItemRow["FinalAmount"] = dtOrdersDetail.Rows[i]["ComboAmount"] + dtOrdersDetail.Rows[i]["TotalPrice"];
}

Upvotes: 0

Views: 102

Answers (2)

Sandeep Rasgotra
Sandeep Rasgotra

Reputation: 622

In this Case you have to correct the code in two place.

  1. Cast the source data table Columns.

    dtItemRow["FinalAmount"] = Convert.ToInt32(dtOrdersDetail.Rows[i]["ComboAmount"]) + Convert.ToInt32(dtOrdersDetail.Rows[i]["TotalPrice"]);

  2. Add the row in data table.

    dtOrderReceipt.Rows.Add(dtItemRow);

So in summary your code look likes as below

 for (int i = 0; i < dtOrdersDetail.Rows.Count; i++)
  {
      DataRow dtItemRow = dtOrderReceipt.NewRow();
      dtItemRow["FinalAmount"] = Convert.ToInt32(dtOrdersDetail.Rows[i]["ComboAmount"]) + Convert.ToInt32(dtOrdersDetail.Rows[i]["TotalPrice"]);
      dtOrderReceipt.Rows.Add(dtItemRow);
  } 

Upvotes: 1

Priyal Pithadiya
Priyal Pithadiya

Reputation: 889

@john, look at the below logic

DataTable table = new DataTable();
table.Columns.Add("TotalPrice", typeof(int));
table.Columns.Add("ComboAmount", typeof(int));

// Here we add five DataRows.
table.Rows.Add(10,10);
table.Rows.Add(20,20);
table.Rows.Add(30,20);

DataTable dtOrderReceipt = new DataTable(); 
dtOrderReceipt.Columns.Add("FinalAmount", typeof(int));

for (int i = 0; i < table.Rows.Count; i++)
{
    DataRow dtItemRow = dtOrderReceipt.NewRow();
    dtOrderReceipt.Rows.InsertAt(dtItemRow, i);
    dtItemRow["FinalAmount"] = (int)table.Rows[i]["ComboAmount"] + (int)table.Rows[i]["TotalPrice"];
}

I think after create a newrow you forgot to Inject it on your Datatable. i.e.

 DataRow dtItemRow = dtOrderReceipt.NewRow();
 dtOrderReceipt.Rows.InsertAt(dtItemRow, i);

Let me know is that logic works for you?

Upvotes: 0

Related Questions