c#窗体格式DataTable with Image列排序

我有DataGridView,我使用DataTables设置datagridview的DataSource。

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控件只能在数据绑定列上排序。

更新:我又添了一列。 它是隐藏的,当使用单击Image列(第一个)时,它会触发ColumnHeaderMouseClick事件。 在那里添加逻辑以对隐藏列进行排序 这只是为我点击的工作。

谢谢,

LE

如果要这样做,则需要使用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("Image").GetImageOrder()) // sort by image type .ThenBy(d => d.Field("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数组具有我刚刚想到的任意排序顺序 - 您可以按照您想要的任何方式重新排序数组,并且图像应该按照您的意愿重新排序。