Faqs on asp.net,c#,vb.net and sqlserver2005

this blog covers all the Faqs related to .net technologies like asp.net,vb.net,c#.net,ajax,javascript and sqlserver2005.

Feb 19, 2008

Delegates example in c#


Using a delegate to pass data between two forms

Introduction

This code demonstrates how you can pass data from one form to another using a delegate. The advantage of using a delegate is that the form from which you want to send the data, doesn't need to know anything about the form that it's sending its data to. This way, you can reuse the same form in other forms or applications.

Details

This is form 1. From this form we display form 2. And from form 2 we send a TextBox back to form 1.



And the code for form 1:



private void btnForm1_Click(object sender, System.EventArgs e)
{
// Create an instance of form 2
Form2 form2 = new Form2();

// Create an instance of the delegate
form2.passControl = new Form2.PassControl(PassData);

// Show form 2
form2.Show();
}

private void PassData(object sender)
{
// Set de text of the textbox to the value of the textbox of form 2
txtForm1.Text = ((TextBox)sender).Text;
}

Form 2 sends the TextBox back to form 1:



public class Form2 : System.Windows.Forms.Form
{
// Define delegate
public delegate void PassControl(object sender);

// Create instance (null)
public PassControl passControl;

private void btnForm2_Click(object sender, System.EventArgs e)
{
if (passControl != null)
{
passControl(txtForm2);
{
this.Hide();
}
}

Of course, using the delegate, you can not only send back the textbox, but other controls, variables or even the form itself, because they are all objects. I hope this is useful.



0 Comments:

Post a Comment

<< Home