2012-03-26 23 views
0

我有DataGridView,我通過使用DataTables設置datagridview的DataSource。c#窗體窗體DataTable與圖像列排序

DataTable dt = new DataTable(); 

     dt.Columns.Add("Image",typeof(Bitmap)); 
     dt.Columns.Add("Col2", typeof(string)); 
     dt.Columns.Add("Col3", typeof(string)); 
     dt.Columns.Add("Col4", typeof(string)); 
     dt.Columns.Add("Col5", typeof(string)); 

     int currentrow = 0; 
     foreach (Dev d in Devs) 
     { 
      dt.Rows.Add(dt.NewRow()); 
      Bitmap bmp = Test(d); 
      dt.Rows[currentrow][0] = bmp; 
      dt.Rows[currentrow][1] = d .ID; 
      dt.Rows[currentrow][2] = d .Name; 
      dt.Rows[currentrow][3] = d .Country; 
      dt.Rows[currentrow][4] = d .State; 
      currentrow++; 
     } 
     datagridview.DataSource = dt; 

此代碼對我的列類型的字符串進行排序,但我想基於圖像進行排序。我想單擊圖像列,它應該根據圖像進行排序。只有三種圖像類型,所以我希望同一圖像應該放在一起以便於顯示。 我搜索了,但還找不到任何解決方案。 任何可以引導我走向正確方向的東西?

遇到錯誤時,我試圖像這樣

datagridview.Sort(dgvFusePTW.Columns[0], ListSortDirection.Ascending); 

錯誤:數據綁定DataGridView控件只能在數據綁定列排序。

更新: 我又添加了一列。它是隱藏的,當使用點擊圖像列(第一個)時,它會觸發ColumnHeaderMouseClick事件。在那裏添加邏輯來排序隱藏的列。 這只是圍繞哪一個點擊我的工作。

謝謝你,

L.E.

回答

1

如果您想這樣做,您需要使用DataView。 (您將需要使用DataSetExtensions來利用LINQ)

// the Bitmap class has the RawFormat property that tells whether 
// it's JPG, PNG, BMP, etc etc 
DataView dv = dt.AsEnumerable() 
    .OrderBy(c => c.Field<Bitmap>("Image").GetImageOrder()) // sort by image type 
    .ThenBy(d => d.Field<string>("Col2")) // then sort by ID... 
    .AsDataView(); 

// take the dataview and bind... 
datagridview.DataSource = dv; 

您還需要定義如下的靜態擴展方法:

public static class ImageHelper 
{ 
    private static ImageFormat[] supportedFormats = new ImageFormat[] 
    { 
     ImageFormat.Bmp, 
     ImageFormat.Gif, 
     ImageFormat.Jpeg, 
     ImageFormat.Png, 
     ImageFormat.Tiff, 
     ImageFormat.Wmf, 
     ImageFormat.Emf, 
     ImageFormat.Exif 
    }; 

    public static int GetImageOrder(this Image target) 
    { 
     for (int i = 0; i < supportedFormats.Length; i++) 
     { 
      if (target.RawFormat.Equals(supportedFormats[i])) 
      { 
       return i; 
      } 
     } 

     // the image format is not within our supported formats array: 
     // just order it to the very end 
     return 9999; 
    } 
} 

注意,supportedFormats陣列有一個任意排列順序,我只是想到 - 你可以任何你想要的方式重新排序陣列,圖像應該按照你的意願重新排序。

+0

它僅基於圖像。不是圖像的類型。所以只有一種圖像。 .ICO。更新的問題。 – 2012-03-26 21:05:33

+0

我試過你的解決方案,但它顯示一個錯誤,如「System.ArgumentException:至少有一個對象必須實現IComparable。」 – 2012-03-26 22:35:26

+0

@ L.E,我更新了答案,現在應該可以工作。 – code4life 2012-03-28 14:37:11