Reputation: 872
Hello i am trying to add items in datatable from gridview if condition is met.
The condition is ReceivedQuantity < OrderedQuantity
The problem is if i have more than one item that met the condition datatable only taking one item.
Code
List<string> PurchaseReturnsItems = new List<string>();
foreach (GridViewRow row in griddelpur.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkSel") as CheckBox);
if (chkRow.Checked)
{
string PurchaseOrderDetailID = row.Cells[1].Text;
string itemcode = row.Cells[2].Text;
string itemname = row.Cells[3].Text;
string UOM = row.Cells[4].Text;
string OrderedQuantity = row.Cells[5].Text;
string ReceivedQuantity = (row.Cells[6].FindControl("txtReceivedQty") as TextBox).Text;
string Comments = (row.Cells[7].FindControl("txtComments") as TextBox).Text;
string ItemID = row.Cells[8].Text;
if (Convert.ToInt32(ReceivedQuantity) < Convert.ToInt32(OrderedQuantity))
{
PurchaseReturnsItems.Add(ItemID);
DataTable tbl = new DataTable();
tbl.Clear();
tbl.Columns.Add("ItemID");
tbl.Columns.Add("ItemCode");
tbl.Columns.Add("UOM");
tbl.Columns.Add("ItemName");
tbl.Columns.Add("ReturnedQuantity");
DataRow dr = tbl.NewRow();
dr["ItemID"] = ItemID;
dr["ItemCode"] = itemcode;
dr["UOM"] = UOM;
dr["ItemName"] = itemname;
dr["ReturnedQuantity"] = Convert.ToInt32(OrderedQuantity) - Convert.ToInt32(ReceivedQuantity);
tbl.Rows.Add(dr);
gridpurahsereturn.DataSource = tbl;
gridpurahsereturn.DataBind();
}
}
}
}
Upvotes: 0
Views: 39
Reputation: 218808
You're doing this for each row:
gridpurahsereturn.DataSource = tbl;
gridpurahsereturn.DataBind();
So after you've done that over and over, the end result is that it will only be bound to whatever the last one was.
Instead, build up your collection of records in the loop and then bind the control to that collection once, after the loop. Something more like this:
// create the data source
DataTable tbl = new DataTable();
tbl.Columns.Add("ItemID");
tbl.Columns.Add("ItemCode");
tbl.Columns.Add("UOM");
tbl.Columns.Add("ItemName");
tbl.Columns.Add("ReturnedQuantity");
// populate the data source
foreach (GridViewRow row in griddelpur.Rows)
{
// all your other logic, then...
DataRow dr = tbl.NewRow();
dr["ItemID"] = ItemID;
dr["ItemCode"] = itemcode;
dr["UOM"] = UOM;
dr["ItemName"] = itemname;
dr["ReturnedQuantity"] = Convert.ToInt32(OrderedQuantity) - Convert.ToInt32(ReceivedQuantity);
tbl.Rows.Add(dr);
}
// use the data source
gridpurahsereturn.DataSource = tbl;
gridpurahsereturn.DataBind();
Upvotes: 1