2009-06-20 32 views
1

XMLの文字列(例コード:*)にシリアル化されたコレクションからDataGridViewを作成します。ImageingとbindingSource.FilterはDataGridViewで連携して動作します

私の要件は、(1)DataGridViewに画像を取得すること、(2)bindingSource.Filter文字列を設定して列の文字列に基づいてテーブルを動的にフィルタリングすること(数千ものエントリ用)です。私の奇妙なXMLの下の文字列のハックは、フィルタのために働いているが、私はde/serializeすることはできません/から文字列を魔法のDataViewを作成することはできません。

質問:(a)RAMからDataGridViewにオブジェクトのDataViewコレクションを取得するより良い方法は、XMLストリング(DataViewを取得する)にシリアライズするよりもですか? .Filterはまだ動作します。 (b).Filterの使用を維持する実行時(特にImage列)にbindingSource/DataViewに項目を追加する別の方法がありますか?

私のテストから、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

(完全リライト)あなたも、XMLを必要としません。あなたがToDataTableを使用する場合、次は正常に動作します:C#2.0は手動getterとsetterが必要ですが、これは動作するので、それは悪いことができるが

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

は、魅力のように働きました私は壊れやすいXML/stringメソッド... blechの代わりに、これを使用するために古いアプリケーションを改訂します。 –

関連する問題