2009-06-20 58 views
1

我从序列化为XML字符串的示例(示例代码:*)填充DataGridView。我需要的是(1)将图像导入DataGridView,(2)设置bindingSource.Filter字符串并根据列中的字符串(可能有数千个条目)动态地过滤表格。我奇怪的XML字符串破解下面的过滤器工作,但我不能de /序列化图像到/从字符串,所以我不能创建一个神奇的DataView其中.Filter工作正常。 (a)是否有更好的方式从RAM获取DataView对象集合到dataGridView中,而不是序列化为XML字符串(以获得DataView)注意.Filter仍然有效。 (b)有没有其他的方法可以在运行时添加东西到bindingSource/DataView(特别是Image列),它保留了.Filter的使用?获取图像和bindingSource.Filter在DataGridView中一起工作

从我的测试中,this way (How to: Bind Objects to Windows Forms DataGridView Controls)使得设置Filter字段无法操作,即什么也不做,没有Exception,没有魔术过滤,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"; 
} 

回答

1

(完全重写)你甚至都不需要XML;如果你使用ToDataTable,以下工作正常:

public class MyType 
{ 
    public string Name { get; set; } 
    public Image Image { get; set; } 
} 
... 
[STAThread] 
static void Main() 
{ 
    List<MyType> list = new List<MyType>(); 
    list.Add(new MyType { Image=Bitmap.FromFile(image1Path), Name="Fred" }); 
    list.Add(new MyType { Image=Bitmap.FromFile(image2Path), Name="Barney" }); 

    DataTable table = list.ToDataTable(); 
    BindingSource bs = new BindingSource(table, ""); 
    bs.Filter = @"Name = 'Fred'"; 
    Application.Run(new Form { 
     Controls = { 
      new DataGridView { 
       DataSource = bs, 
       Dock = DockStyle.Fill} 
     } 
    }); 
} 
+0

工作就像一个魅力,虽然C#2.0中需要手动getter和setter方法,但它可能会更糟,因为这工作。我将重新构建一个旧的应用程序来使用它,而不是脆弱的XML /字符串方法...... blech。 – 2009-06-22 23:45:02

相关问题