i came across some ugly bug with DataGridView and PictureBox (for instance) when bound to the same filtered sorted table. May be i'm missing something, please help to understand
let's say i created
BindingSource bs = new BindingSource();
BindingSource.DataSource = myTable;
my table has the following structure
ID int (Primary Key)
NAME varchar
ACTIVE short
PICTURE blob
with only one row e.g
Name = 'George';
Active = 1;
Picture = some picture
i set filter and sorting
bs.Filter = "Active=1";
bs.Sort = "Name";
i load the table into DataGridView
dataGridView1.DataSource = bs;
and bind some controls (PicturBox among them) to the table fields
Binding b = new Binding("Image", bindingNavigator1.BindingSource, "picture");
b.Format += new ConvertEventHandler(b_Format);
b.Parse += new ConvertEventHandler(b_Parse);
pictureBox1.DataBindings.Add(b);
in Format and Parse events i format the Image to properly display images and nulls
void b_Format(object sender, ConvertEventArgs e)
{
if (e.DesiredType == typeof(Image))
{
if (DBConvert.isNull(e.Value))
e.Value = new Bitmap(1, 1);
else
{
using (MemoryStream m = new MemoryStream(e.Value as byte[]))
{
m.Position = 0;
e.Value = Image.FromStream(m);
}
}
}
}
void b_Parse(object sender, ConvertEventArgs e)
{
if (e.DesiredType == typeof(byte[]))
{
using (MemoryStream m = new MemoryStream())
{
(e.Value as Image).Save(m, ImageFormat.Png);
byte[] b = new byte[m.Length];
m.Position = 0;
m.Read(b, 0,b.Length);
e.Value = b;
}
}
}
Now i add a new row which has by default Active = null, and Picture=null that's why i modify filter to see both rows, as long as new row is not saved
DataRow Row = myTable.NewRow();
Row["ID"] = 1000;
//hier Active and Picture are null by default
myTable.Rows.Add(Row);
bs.Filter += " or ID=1000";
When the new row is added, it becomes the first row in grid because of sorting by name. Now I edit the name value of the new record, i set it to "Test" making it become the second row in grid (again because of sorting by name, another record has "George" in Name). And now the Bug - as soon as Grid losses focus, sorting occurs, the values of old row with "George" (Active and Picture) a overwritten with values of new row (setting Active and Picture to null) - it causes the old record do disappear from filter and makes Grid scream "Index out of range". And now attention: if
1) no sorting and filter apllied
2) the new record is added after the old one (causing no new sorting)
3) only DataGridView is bound to table
4) only PictureBox and other Controls (TextBox, CheckBox) are bound to the table
everything works just fine.
I also noticed some strange thing, the problem of combined binding applies only to some controls, e.g. PictureBox or modified CheckBox (which allows null). It can be my error but ... without each other (Controls and Grid) things work just fine.