我有DataGridview,我过滤了它的一些行,我需要将新的数据源保存到新的DataTable,由于某些原因我的当前代码不起作用,这里我是怎样的试图转换它。
(LogGridView.DataSource as DataTable).DefaultView.RowFilter = string.Format("Type IN({0}) AND Date >= {1} AND Date <= {2} AND Content {3} '%{4}%'", typeFilter, startDate, endDate, likeQuery,keywordFilter.Text);
this.LogGridView.Sort(this.LogGridView.Columns[0], ListSortDirection.Ascending);
FilteredTable = LogGridView.DataSource as DataTable;
public DataTable FilteredTable
{
get;
set;
}
任何想法为什么它不起作用
由于
答案 0 :(得分:1)
您在此处看到的是,应用过滤器和排序后,虽然DataTable
按预期显示,但源DataGridView
仍未更改。这是设计的。所以打电话:
FilteredTable = LogGridView.DataSource as DataTable;
只需将FilteredTable
设置为与原始表格相同。
相反,我们将创建一个方法:
DataGridView
排序相同的过滤字符串和等效排序字符串从原始表中选择行。如下所示:
private DataTable CloneAlteredDataTableSource(DataGridView dgv)
{
DataTable dt = dgv.DataSource as DataTable;
if (dt == null)
{
return null;
}
DataTable clone = new DataTable();
foreach (DataColumn col in dt.Columns)
{
clone.Columns.Add(col.ColumnName, col.DataType);
}
string order = string.Empty;
switch (dgv.SortOrder)
{
case SortOrder.Ascending: order = "ASC"; break;
case SortOrder.Descending: order = "DESC"; break;
}
string sort = dgv.SortedColumn == null ? string.Empty : string.Format("{0} {1}", dgv.SortedColumn.Name, order);
DataRow[] rows = dt.Select(dt.DefaultView.RowFilter, sort);
foreach (DataRow row in rows)
{
object[] items = (object[])row.ItemArray.Clone();
clone.Rows.Add(items);
}
return clone;
}
用法:
(this.LogGridView.DataSource as DataTable).DefaultView.RowFilter = string.Format("Type IN({0}) AND Date >= {1} AND Date <= {2} AND Content {3} '%{4}%'", typeFilter, startDate, endDate, likeQuery,keywordFilter.Text);
this.LogGridView.Sort(this.LogGridView.Columns[0], ListSortDirection.Ascending);
this.FilteredTable = this.CloneAlteredDataTableSource(this.LogGridView);