c# - 如何将值存储在列表或数组中并将所有值绑定到数据表然后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?
解决方案
你的代码看起来不太好。首先,您正在执行循环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();
}
推荐阅读
- google-slides-api - Google Slides API batchUpdate 返回 500 内部错误
- python - Tensorflow 密集模型不断输出相同的输出
- java - 使用 WSDL2Java 时添加默认值(不修改模式)?
- c# - 根据特定单元格中的数据组合数据表中的行
- python - 显示隐藏小部件后如何将所有内容保持在正确位置?
- mongodb - 如何在下一个 js 应用程序的客户端显示猫鼬模式验证错误消息?
- java - 在 jgit 中使用 RevWalk 的 parseCommit 方法得到 NullPointerException
- node.js - 根据 _id 更新子数组中的所有元素
- python - 即使字符串模式匹配,re.match 也会返回 false
- angular - 如何在模板驱动的表单中以角度添加空格验证