
40
❘
CHAPTER 2 Creating Visual Web Parts
Adding Code
The main method within the user control code-behind is the Page_Load method. You may add
code in this method, as shown in Figure2-7, or call other custom methods to populate the control.
A good practice is to implement error handling within this method and make calls to other custom
methods to perform the logic within your user control.
FIGURE27: Adding controls in Source View
A common condition to check is the Page.IsPostBack. Depending on the functionality of your user
control, you may or may not want to perform actions if there is a post back on the page in which the
web part lives. A sample
Page_Load method may look like the following:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
SetControls(); //custom method
}
catch (Exception webPartException)
105054c02.indd 40 1/10/12 3:34 PM