I have a DataGridView
which has been bound to a generic BindingList
. I want to be able to apply sort and search on columns of type DataGridViewImageColumn
. The basic idea is to store a name into the image Tag
and use is for sorting and searching. How can I do that?
It seems several ways to do it:
- Creating a new class inheriting
System.Drawing.Image
and making it comparable.Image
is an abstract class and if I inherit from it (as well asIComparable
interface), I'll encounter with this error message: The type 'System.Drawing.Image' has no constructors defined. What's the problem here? Image is anabstract
not asealed
class, but it doesn't allow me to inherit it!
Using protected override
ApplySortCore
method of inherited class fromBindingList<T>
.This method is like so:
class MyBindingList<T> : BindingList<T> { ... protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction) { if (prop.PropertyType.Equals(typeof(Image))) { /* I have no idea! */ } } }
- Creating a new
DataGridViewColumn
inheriting fromDataGridViewImageColumn
.- This doesn't seem to be easy and may be used if other ideas are unusable.
Thanks 开发者_Go百科in advance
Create a class (X) that incapsulates System.Drawing. Image + ImageAlias string property. Bind your image column to X.Image and search over X.ImageAlias.
Sorry but don't have a coding tool on my hands to provide an example, but this is a basic idea.
Hope this helps.
I found the way!
MyBindingList
class MyBindingList<T> : BindingList<T>
{
...
protected override void ApplySortCore(PropertyDescriptor prop,
ListSortDirection direction)
{
if (prop.PropertyType.Equals(typeof(Image)))
{
_SortPropertyCore = prop;
_SortDirectionCore = direction;
var items = this.Items;
Func<T, object> func =
new Func<T, object>(t => (prop.GetValue(t) as Image).Tag);
switch (direction)
{
case ListSortDirection.Ascending:
items = items.OrderBy(func).ToList();
break;
case ListSortDirection.Descending:
items = items.OrderByDescending(func).ToList();
break;
}
ResetItems(items as List<T>);
ResetBindings();
}
else
{
...
}
}
private void ResetItems(List<T> items)
{
base.ClearItems();
for (int itemIndex = 0; itemIndex < items.Count; itemIndex++)
{
base.InsertItem(itemIndex, items[itemIndex]);
}
}
}
MyDataObject
class MyDataObject : INotifyPropertyChanged
{
...
public Image MyProp
{
get
{
return CreateComparableImage(myImage, "myImage");
}
}
private Image CreateComparableImage(Image image, string alias)
{
Image taggedImage = new Bitmap(image);
taggedImage.Tag = alias;
return taggedImage;
}
}
Form
class MyForm : Form
{
...
void BindDGV()
{
dataGridView1.Columns["myColumnName"].DataPropertyName = "MyProp";
dataGridView1.DataSource = MyBindingList<MyDataObject>(...);
}
}
精彩评论