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

时间:2012-03-26 20:49:58

标签: c# sorting datagridview

我有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事件。在那里添加逻辑以对隐藏列进行排序 这只是为我点击的工作。

谢谢你,

L.E。

1 个答案:

答案 0 :(得分: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数组有一个我想到的任意排序顺序 - 您可以按照自己的方式对数组进行重新排序,图像应该按照您的意愿重新排序。

相关问题