![](/img/trans.png)
[英]How can I get the distinct values in a Gridview column and store them into a Datatable or list?
[英]How to store values in a list or array and bind all to datatable then 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
将其绑定到网格中,您的代码只是在heap
创建一个 DataTable ,添加一些 Rows 并将其保留到Garbage Collector
中删除它,您甚至没有使用它。 Third, considering you are doing a method to add a new item on the GRidView, remove the initilization of your list to the scope of your class and keep it a valid instance (or static one if it is the case):
// 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.