首页 > 解决方案 > 如何将值存储在列表或数组中并将所有值绑定到数据表然后gridview

问题描述

private void ListViewAddMethod(string fItem, string sItem, string tItem, string foItem)
    {
        List<ReportList> alstNames = new List<ReportList>();
        alstNames.Add(new ReportList(fItem, sItem, tItem, foItem));

        DataTable dt = new DataTable();

        dt.Columns.Add("Particulars", typeof(string));
        dt.Columns.Add("Amount", typeof(string));
        dt.Columns.Add("Particulars1", typeof(string));
        dt.Columns.Add("Amount1", typeof(string));

        foreach (var lstNames in alstNames)
        {
            // Add new Row - inside the foreach loop - to enable creating new row for each object.
            DataRow row = dt.NewRow();
            row["Amount"] = fItem;
            row["Particulars"] = sItem;
            row["Particulars1"] = tItem;
            row["Amount1"] = foItem;
            dt.Rows.Add(row);

            dgvProfitAndLoss.DataSource = alstNames;
            dgvProfitAndLoss.DataBind();
        }

    }

这仅返回最近添加的行并忽略其他行。如何从传递给方法的参数创建数组并将它们绑定到gridview?

标签: c#asp.netarrays.netloops

解决方案


你的代码看起来不太好。首先,您正在执行循环alstNames并将其绑定到此循环的每次迭代中的 gridview 中。其次,您不需要将DataTable其绑定到网格中,并且您的代码只是在 上创建一个 DataTable heap,添加一些 Rows 并保留它以Garbage Collector将其删除,您甚至没有使用它。第三,考虑到您正在执行一种在 GRidView 上添加新项目的方法,请将列表的初始化删除到类的范围并使其保持有效实例(如果是这种情况,则为静态实例):

// declare the list output of the method
private private List<ReportList> alstNames = new List<ReportList>();

private void ListViewAddMethod(string fItem, string sItem, string tItem, string foItem)
{    
    // add the ReportList on the list
    alstNames.Add(new ReportList(fItem, sItem, tItem, foItem));

    // bind it on the gridView
    dgvProfitAndLoss.DataSource = alstNames;
    dgvProfitAndLoss.DataBind();
}

推荐阅读