【发布时间】:2009-06-20 00:32:08
【问题描述】:
我从序列化为 XML 字符串的集合填充 DataGridView(示例代码:*)。
我的要求是 (1) 将图像放入 DataGridView 和 (2) 设置 bindingSource.Filter 字符串并根据列中的字符串动态过滤表的能力(可能有数千个条目)。下面我奇怪的 XML to string hack 适用于 Filter 但我无法将图像反序列化到字符串/从字符串反序列化,因此我无法创建一个 .Filter 正常工作的魔术 DataView。
问题:(a) 有没有比序列化为 XML 字符串(以获取 DataView)更好的方法从 RAM 中获取对象的 DataView 集合到 dataGridView 中需要注意的是 .Filter 仍然工作。 (b) 是否有另一种方法可以在运行时向 bindingSource/DataView 添加内容(尤其是 Image 列),从而保留 .Filter 的使用?
根据我的测试,做事情this way (How to: Bind Objects to Windows Forms DataGridView Controls) 使设置过滤器字段无法操作,即什么都不做,没有异常,没有魔法过滤,nada。
(*)
// objects in each row
[Serializable]
public class GradorCacheFile
{
public Bitmap image;
public string filename;
// to make it serializable
public GradorCacheFile()
{
}
public GradorCacheFile(GradorCacheFile old)
{
this.filename = old.filename;
this.image = old.image;
}
}
// snippet of class:
public List<GradorCacheFile> files = null;
void Process()
{
GradorCacheFiles gcf = new GradorCacheFiles();
gcf.AddRange(this.files);
XmlSerializer xs = new XmlSerializer(typeof(GradorCacheFiles));
StringWriter sw = new StringWriter();
xs.Serialize(sw, gcf);
sw.Close();
string xml = sw.ToString();
StringReader reader = new StringReader(xml);
DataSet ds = new DataSet();
ds.ReadXml(reader);
if (ds.Tables.Count < 1)
return;
DataTable dt = ds.Tables[0];
DataView dv = new DataView(dt);
this.bindingSource = new BindingSource();
this.bindingSource.DataSource = dv;
this.dataGridView.DataSource = this.bindingSource;
int rows = this.dataGridView.Rows.Count;
if (rows == 0)
return;
this.dataGridView.Columns[0].HeaderText = "Image";
this.dataGridView.Columns[1].HeaderText = "File";
}
【问题讨论】:
标签: c# .net user-interface datagridview