代码之家  ›  专栏  ›  技术社区  ›  Jared Updike

获取图像和bindingSource.Filter在DataGridView中协同工作

  •  1
  • Jared Updike  · 技术社区  · 16 年前

    我从序列化为XML字符串的集合填充DataGridView(示例代码:*)。

    我的要求是(1)将图像放入DataGridView,以及(2)能够设置bindingSource.Filter字符串,并根据列中的字符串(可能有数千个条目)动态筛选表。下面我的奇怪的XML到字符串攻击适用于Filter,但我无法将图像反序列化到字符串或从字符串中反序列化,因此我无法创建一个神奇的DataView,其中.Filter可以正常工作。

    问题:(a)与序列化为XML字符串(获取数据视图)相比,是否有更好的方法将对象的DataView集合从RAM获取到dataGridView 但要注意,过滤器仍然可以工作

    通过我的测试,做一些事情 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";
    }
    
    1 回复  |  直到 16 年前
        1
  •  1
  •   Community CDub    8 年前

    (完全重写)您甚至不需要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}
            }
        });
    }