Wednesday, September 21, 2005

Handeling server control event from page itself in .NET

Let me define the problem statement. Say, we have address control having address1, address2, city, state and some other fields. This post answers to handle "save" button click event from page itself. You already have the event handler on control code behind, but to handle it from main page (where your control resides) is a bit tricky. Here is a step by step guide for a newbie who want to create server control and would like to wire events.

> Declare an public event in to your control, like...
public event CommandEventHandler SaveCommand;

> Add btnSave click event handler, and also the defination...
btnSave.Click += new EventHandler(btnSave_Click);
private void btnSave_Click(object sender, EventArgs e)
Button button = sender as Button;
if (button != null)
CommandEventArgs args = new CommandEventArgs(button.CommandName, button.CommandArgument);


> Add OnSaveCommand function...
protected virtual void OnSaveCommand(CommandEventArgs e)
if (SaveCommand != null)
SaveCommand(this, e);

> Now you can have the event handler in your page. Just click on control from page, add your code...
private void AddressControl1_SaveCommand(object sender, System.Web.UI.WebControls.CommandEventArgs e)
// my code..


No comments: