数据表中的多条记录

时间:2016-07-30 12:03:26

标签: c# asp.net datatable

你好我想在条件满足的情况下从gridview添加数据表中的项目。

条件是ReceivedQuantity< OrderedQuantity

问题是,如果我有多个符合条件数据表的项目只需要一个项目。

代码

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();
            }
        }
    }


}

1 个答案:

答案 0 :(得分:1)

您为每一行执行此操作:

gridpurahsereturn.DataSource = tbl;
gridpurahsereturn.DataBind();

所以在你一遍又一遍地完成之后,最终结果是它只会被绑定到最后一个。

相反,在循环中构建您的记录集合,然后将控件绑定到该集合一次循环之后。更像是这样:

// 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();