【问题标题】:How to store values in a list or array and bind all to datatable then gridview如何将值存储在列表或数组中并将所有值绑定到数据表然后gridview
【发布时间】:2020-11-29 12:20:36
【问题描述】:
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();
        }

    }

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

【问题讨论】:

  • 首先,您不需要数据表。您可以将 List 直接绑定到 GridView。而且您需要将dgvProfitAndLoss.DataSource 放在循环之外!

标签: c# asp.net arrays .net loops


【解决方案1】:

您的代码看起来不太好。首先,您正在对alstNames 进行循环,并在此循环的每次迭代中将其绑定到gridview 中。其次,您不需要DataTable 将其绑定到网格中,您的代码只是在heap 上创建一个DataTable,添加一些行并将其保留到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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    相关资源
    最近更新 更多