BeginInit() and EndInit() in Generated Code Region

G

Greg Dunn

When I create a form using the DataForm Wizard (VS 2003), the following
lines of code get generated near the top of the
Windows Form Designer generated code region:

CType(Me.objdsDataForm,
System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.grdtitles,
System.ComponentModel.ISupportInitialize).BeginInit()

The corresponding EndInit() statements get generated near the bottom of the
region:

CType(Me.objdsDataForm,
System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.grdtitles, System.ComponentModel.ISupportInitialize).EndInit()

Can someone explain to me what these statements do? Also, since the DataSet
and DataGrid objects both implement the ISupportInitialize interface, why do
those objects need to be converted to the interface type before the
BeginInit and EndInit methods are called? Why not just call those methods
directly on the DataSet and DataGrid objects?

Thanks.
 
D

Dmitriy Lapshin [C# / .NET MVP]

Can someone explain to me what these statements do?

These statements prevent a control from reflecting changes made to each of
its properties set during the InitializeComponent phase. This improves
performance and helps avoiding unwanted effects.
When EndInit is called, all the changes made are applied at once. You can
think of it as of
an atomic unit of initialization.
Also, since the DataSet
and DataGrid objects both implement the ISupportInitialize interface, why do
those objects need to be converted to the interface type before the
BeginInit and EndInit methods are called? Why not just call those methods
directly on the DataSet and DataGrid objects?

It is not guaranteed that these methods are visible as public methods of a
class
event if the class implements the ISupportInitialize interface. Consider the
following
example:

public class MyControl: UserControl,
ISupportInitialize
{
void ISupportInitialize.BeginInit(...)
{
// ...
}

void ISupportInitialize.EndInit(...)
{
// ...
}
}

Therefore the explicit cast to ISupportInitialize ensures the methods will
be accessible.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top