我尝试过滤一个返回DataTable的方法的结果,按某个列值(DateTime类型)并将它们插入两个不同的DataTables,如下所示:
var vAllItems = myClass.GetAllResults(x,y,z);
DataTable dtExpiredItems = new DataTable();
DataTable dtActiveItems = new DataTable();
var expiredItems = vAllItems.AsEnumerable().Where(r => r.Field<DateTime?>("ExpDate") <= DateTime.Now && r.Field<DateTime?>("ExpDate").HasValue);
var activeItems = vAllItems.AsEnumerable().Where(r => r.Field<DateTime?>("ExpDate") > DateTime.Now || !r.Field<DateTime?>("ExpDate").HasValue);
foreach(DataRow row in expiredItems)
dtExpiredItems.Rows.Add(row);
foreach (DataRow row in activeItems)
dtActiveItems.Rows.Add(row);
rptExpiredItems.DataSource = dtExpiredItems;
rptExpiredItems.Bind();
pchExpiredItems.Visible = dtExpiredItems.Rows.Count > 0;
rptActiveItems.DataSource = dtActivetItems;
rptActiveItems.Bind();
pchActiveItems.Visible = dtActiveItems.Rows.Count > 0;
事情是,在第二个foreach循环中发生以下错误:
This row already belongs to another table.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: This row already belongs to another table.
任何帮助表示赞赏!谢谢!
答案 0 :(得分:1)
DataRow只能属于一个 Dim bs As New BindingSource
bs.DataSource = 'Here goes the datasource of your gridview'
bs.Filter = gridCreation.Columns(i).HeaderText.ToString() + ">=" + TextBox1.Text + " and " + gridCreation.Columns(i).HeaderText.ToString() + "<=" + TextBox2.Text
//i would be the column number where your location row is.
//Remember that the index starts on 0
DataGridView.DataSource = bs
DataGridView.DataBind()
,您应该从给定的行值创建一个新行。
使用DataTable
的{{1}}属性获取值并传递ItemArray
作为输入以创建新行。
DataRow
或使用object[]
dtExpiredItems.Rows.Add(row.ItemArray);
另一种选择是使用CopyToDataTable
(DataTable)扩展来从ImportRow
输出创建新表,然后使用新表进行绑定。
dtExpiredItems.ImportRow(row);
答案 1 :(得分:1)
您正在执行以下操作
dtExpiredItems.Rows.Add(row);
dtActiveItems.Rows.Add(row);
你可以改为
dtExpiredItems.ImportRow(row);
dtActiveItems.ImportRow(row);