User288213138 posted
Hi asplearning,
According to your description, I made a demo for you.
I traverse the data in the table twice. The first one is to read all the data in the table.
The second one is to judge whether the value in target table is the same as that in the first one. If so, combine them.
The code:
Aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind();
}
}
public void Bind()
{
DataTable table = new DataTable();
table.Columns.Add(new DataColumn("productId", typeof(string)));
table.Columns.Add(new DataColumn("unitId", typeof(string)));
table.Columns.Add(new DataColumn("price", typeof(string)));
table.Columns.Add(new DataColumn("quantity", typeof(string)));
table.Rows.Add("1", "u1", "p1", "1");
table.Rows.Add("1", "u1", "p1", "1");
table.Rows.Add("2", "u2", "p2", "1");
DataTable table1 = new DataTable();
table1.Columns.Add(new DataColumn("productId", typeof(string)));
table1.Columns.Add(new DataColumn("unitId", typeof(string)));
table1.Columns.Add(new DataColumn("price", typeof(string)));
table1.Columns.Add(new DataColumn("quantity", typeof(string)));
foreach (DataRow item in table.Rows)
{
bool hasRow = false;
foreach (DataRow item2 in table1.Rows)
{
if (item2["productId"].ToString() == item["productId"].ToString() & item2["unitId"].ToString() == item["unitId"].ToString() & item2["price"].ToString() == item["price"].ToString())
{
item2["productId"] = item2["productId"];
item2["unitId"] = item2["unitId"];
item2["price"] = item2["price"];
item2["quantity"] = Convert.ToInt32(item2["quantity"]) + Convert.ToInt32(item["quantity"]);
hasRow = true;
break;
}
}
if (!hasRow)
{
table1.Rows.Add(item["productId"], item["unitId"], item["price"], item["quantity"]);
}
}
GridView1.DataSource = table;
GridView1.DataBind();
GridView2.DataSource = table1;
GridView2.DataBind();
}
Aspx:
<div>
<asp:GridView ID="GridView1" runat="server"></asp:GridView><br /><br />
<asp:GridView ID="GridView2" runat="server"></asp:GridView>
</div>
The result:

Best regards,
Sam