26
Simplest solution to pass values from one user control to another user control on a web page Buy proven .NET Trainings on www.ITFunda.Com (Adv) Introduction Always there comes a requirement where we developers need to pass values to between different user controls which are parts of a webpage or even sometimes there comes a requirement where we need to pass values from user control to the container page. The job is easy when we have to pass values which are there on the user controls by exposing the value fields as properties of the user control. However it is challenging when on certain event the values should get passed. Solution The simplest solution to this situation I found is to handle this by use of events and delegates. Let me explain the solution with one simple example. For example on a content page I am having two user controls e.g. UC1 and UC2. Contents of UC1 are: 1. List box having list of States 2. List box having list of Cities in the State (Pre-condition: User selects State from ListBoxStates and respective cities in the selected state gets populated in the ListBoxCities) 3. Button control, which will be used for confirming the user’s selections. Let us name it as btnSelect. Contents of UC2 are: 1. List of selected cities from UC1. Let us name it as ListBoxSelectedCities. Our requirement is whenever user selects (multiple) cities from ListBoxCities and clicks on btnSelect in UC1 then the selected cities should get populated in ListBoxSelectedCities in UC2. In UC1, we need to declare the following objects: public delegate void PassSelectedValues(string[] selectedCities); public event PassSelectedValues citiesSelected; Now in UC1 from the button click event we can raise citiesSelected event, delegate of which will carry the required values which we need to pass in between UC1 and UC2. In button click event we have to create the list of selected cities from ListBoxCities and we have to raise the citiesSelected event like this:

Pass Values From One User Control to Another User Control on a Web Page

  • Upload
    praveen

  • View
    107

  • Download
    3

Embed Size (px)

Citation preview

Page 1: Pass Values From One User Control to Another User Control on a Web Page

Simplest solution to pass values from one user control to another user control on a web page

Buy proven .NET Trainings on www.ITFunda.Com (Adv)

IntroductionAlways there comes a requirement where we developers need to pass values to between different user controls which are parts of a webpage or even sometimes there comes a requirement where we need to pass values from user control to the container page.The job is easy when we have to pass values which are there on the user controls by exposing the value fields as properties of the user control. However it is challenging when on certain event the values should get passed.

Solution

The simplest solution to this situation I found is to handle this by use of events and delegates. Let me explain the solution with one simple example.For example on a content page I am having two user controls e.g. UC1 and UC2. Contents of UC1 are:1. List box having list of States2. List box having list of Cities in the State (Pre-condition: User selects State from ListBoxStates and respective cities in the selected state gets populated in the ListBoxCities)3. Button control, which will be used for confirming the user’s selections. Let us name it as btnSelect.Contents of UC2 are:1. List of selected cities from UC1. Let us name it as ListBoxSelectedCities.Our requirement is whenever user selects (multiple) cities from ListBoxCities and clicks on btnSelect in UC1 then the selected cities should get populated in ListBoxSelectedCities in UC2.

In UC1, we need to declare the following objects:

public delegate void PassSelectedValues(string[] selectedCities);public event PassSelectedValues citiesSelected;

Now in UC1 from the button click event we can raise citiesSelected event, delegate of which will carry the required values which we need to pass in between UC1 and UC2. In button click event we have to create the list of selected cities from ListBoxCities and we have to raise the citiesSelected event like this:

citiesSelected(selectedCities);

Here selectedCities is an array of strings which we have to create by looping through the ListBoxCities.

We have to declare a public property in UC2 which can be used to set the ListBoxSelectedCities. For example in UC2:

Page 2: Pass Values From One User Control to Another User Control on a Web Page

public string[] SelectedCitiesList{ set { ListBoxSelectedCities.DataSource = value; ListBoxSelectedCities.DataBind(); }}

In the content page we have to declare the event handler for the event (citiesSelected) which we have raised from UC1. Thus in content page on page load we have to declare the handler of this event like this:

UC1.citiesSelected += new citiesUserControl.PassSelectedValues(passValuesHandlerMethod);

This handler method in the content page should have the same signature as of the delegate’s signature defined in UC1.

protected void passValuesHandlerMethod(string[] selectedCities){ }

Now from this method we can pass the value coming from UC1 to UC2 like this:

protected void passValuesHandlerMethod(string[] selectedCities){   UC2.SelectedCitiesList = selectedCities;}

In this way whichever values we are selecting in UC1 will get passed to UC2.

Conclusion

In this article we have seen that how to pass values between different user controls on a webpage using events and delegates. Same concept can be applied for passing value from user control to the content page.

 

Page 3: Pass Values From One User Control to Another User Control on a Web Page

Introduction

This article describes a simplified approach to allowing communication between forms without the use of events and delegates. The approach demonstrated is adequate if the application uses a single instance of a form and allows the creation of a single instance of a dialog used to pass data to the main calling form. If you need to broadcast the data generated by a dialog to multiple form listeners, you will still need to work with events and delegates; this approach is only valid if there is a one on one relationship between the two interactive forms.

Figure 1. Data entered in the Right Form immediately appears in the Left Form

Getting Started.

There is a single Win Forms application included with this download. You may open the project and examine the files and code if you wish; however, the code is quite simple and will be described in the following sections of this document. All examples were written using Visual Studio 2005 and are in C#; the same code could also be used in earlier versions of Visual Studio.

In general the application contains only two forms. Form 1 opens with the application and it contains five label controls which act as targets for data entered from Form 2. Form 1 is titled, "Originator" and Form 2 is labeled, "Data Entry". 

Code: Form 1.

Form 1 contains five labels and a button. The five labels carry default text whenever an instance for Form 1 initially created. The labels are set to display "Name", "Street", "City", "State", and "Zip Code". There is also a single button contained on the form. Whenever this button is clicked, a new instance of Form 2 is created. Form 2 has an overloaded constructor

Page 4: Pass Values From One User Control to Another User Control on a Web Page

and it accepts an object of type Form 1 as an argument. By passing the current Form 1 to instances of Form 2 through the constructor, it is possible to communication directly between the forms without adding events and delegates.

The entire body of code contained in Form 1 is as follows:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;

namespace LimitedDataXfer{ public partial class Form1 : Form { public Form1() { InitializeComponent(); }

private void btnOpenForm_Click(object sender, EventArgs e) { Form2 f = new Form2(this); f.Show(); } }}

Looking over the code you will not that nothing but the default imports are included in the definition of the form class. The class definition is also in the default configuration. The only code added to the class is that used to handle the single buttons click event. In that click event handler, a new instance of Form 2 is created and it is pass "this" as an argument. After the current Form 1 is passed to the form 2 constructor as an argument, the Form 2 instance is displayed to the user.

By passing the current Form 1 object to Form 2 in this manner, Form 2 may directly access any property in Form 1 instance to include each of the labels that will be populated through Form 2. This will allow communication between the two forms without the definition an delegates or events used to handle that communication.

Code: Form 2.

The code behind Form 2 is also very simple. This form also contains only the default imports and the class declaration is also per the default configuration. The form does contain an overloaded constructor which is configured to accept an object of type Form 1 as an argument. If a Form 1 object is passed to the constructor, a local object of type Form 1 will be set to point to this passed in form.

The entire body of code contained in this class is as follows:

using System;using System.Collections.Generic;using System.ComponentModel;

Page 5: Pass Values From One User Control to Another User Control on a Web Page

using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;

namespace LimitedDataXfer{ public partial class Form2 : Form { Form1 f;

public Form2() { InitializeComponent(); }

public Form2(Form1 fr1) { InitializeComponent(); f = new Form1(); f = fr1; }

private void Form2_Load(object sender, EventArgs e) { }

private void textBox1_TextChanged(object sender, EventArgs e) { f.lblName.Text = textBox1.Text; }

private void textBox2_TextChanged(object sender, EventArgs e) { f.lblStreet.Text = textBox2.Text; }

private void textBox3_TextChanged(object sender, EventArgs e) { f.lblCity.Text = textBox3.Text; }

private void textBox4_TextChanged(object sender, EventArgs e) { f.lblState.Text = textBox4.Text; }

private void textBox5_TextChanged(object sender, EventArgs e) { f.lblZip.Text = textBox5.Text; } }}

Page 6: Pass Values From One User Control to Another User Control on a Web Page

In the code above, you will note that the overloaded constructor is configured to accept the Form 1 object as an argument and you can see that the local Form 1 object is set to this passed in Form 1 object. The remainder of the code is merely used to handle the text changed event for each of the text boxes contained in the Form 2 object. Whenever the text in any of the text boxes is changed, the current value of that text box is immediately passed to the appropriate label control in the Form 1 object.

When the application is run and the Form 2 object is created, typing into any of the text boxes will immediately update the Form 1 object's applicable label control.

Summary.

This example demonstrates a simplified approach to transmitting data between forms without any reliance upon delegates and events. Since the approach shown requires passing the calling form as an argument to the new form which in turn will operate on the calling form, the approach is limited to instances where that relationship may be enforced and where communication between the two forms is adequate. If you need to broadcast information to multiple forms, you will need to rely on events and delegates to accomplish the task.

Page 7: Pass Values From One User Control to Another User Control on a Web Page

Passing Data between Windows FormsBy salysle | 27 Jan 2007 Passing Data between Windows Forms

Download source files - 96 Kb

Introduction

This article provides a simple example of using delegates and events to transfer data between Windows forms. The example provided contains three separate forms; the main form interacts with the other two forms by responding to events generated by instances of the other two forms.

In order to communicate between the forms, each of forms capable of generating an event contains declarations for a delegate and an event. A delegate may be thought of as a type safe function pointer and delegates are associated with methods that bear the same signature. An event is a device used to notify listening objects that something has happened; events are associated with a delegate when instantiated.

Through the use of delegates and events it is possible to communicate values between forms in a Win Forms application.

Figure 1. Using Delegates and Events to Communicate Between Forms

Getting Started.

There is a single solution included with this download, the solution contains a Win Forms project called �PassBetweenForms�; this project contains three forms, one main form that creates instances of the other two forms and responds to events raised by the instances of those two forms.

Page 8: Pass Values From One User Control to Another User Control on a Web Page

For the sake of an example, the main form (frmMain) contains an area used to contain an identity (first, middle, and last name) and an area used to display an address (street, city, state, and zip code). The values for these areas are displayed on the form but the form does not allow the user to enter the text directly into the form.

In order to set the values associated with the ID or Address sections of the main form, the user must click on a �Set� button which creates an instance of either the �frmID� form or the �frmAddress� form. When data is entered into and submitted from either of these forms, the main form listens for an update event and then loads the information from either of the other two forms into the main form�s associated text boxes.

Figure 2. Solution Explorer

Code: The Address Form

Rather than starting with the main form, first take a look at the Address form. The Address form contains three parts that make communication with the main form possible. Those parts are the delegate and event declarations and the declaration of a class used to define the content of the event arguments made available to the event listener when the event is fired.

The class declaration contains only the default imports and after the imports, the delegate and event are declared:

Collapse | Copy Code

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

Page 9: Pass Values From One User Control to Another User Control on a Web Page

namespace PassBetweenForms

{

public partial class frmAddress : Form

{

// add a delegate

public delegate void AddressUpdateHandler(

object sender, AddressUpdateEventArgs e);

// add an event of the delegate type

public event AddressUpdateHandler AddressUpdated;

public frmAddress()

{

InitializeComponent();

}

}

}

The signature of the delegate is pretty standard in this example, it contains the sender as an object and the event arguments; it is possible to use different signatures and return types, the approach used here is just a convenient way to return several values when an event is raised. The �AddressUpdateEventArgs� is the class used to provide a customized argument list to the project. This class inherits from the �EventArgs� class and contains properties used to capture the values provided on the form and to make them available to the listener when the event is fired.

The next bit of code in this class is used to handle the OK button�s click event. When the OK button is clicked from this form, all of the text box values contained in the form are passed to string variables. Once the value have been collected, the custom event argument class is instantiated and, through its constructor, passed each of the values captured from the form. The address updated event is then fired and the event arguments are passed on to the listeners with the event; once the event is raised, the form is closed by calling the dispose method:

Collapse | Copy Code

private void btnOkay_Click(object sender, EventArgs e)

{

// this button click event handler will raise the

// event which can then intercepted by any listeners

// read the textboxes and set the member

Page 10: Pass Values From One User Control to Another User Control on a Web Page

// variables

string sNewStreet = txtStreet.Text;

string sNewCity = txtCity.Text;

string sNewState = txtState.Text;

string sNewZipCode = txtZipCode.Text;

// instance the event args and pass it each value

AddressUpdateEventArgs args =

newAddressUpdateEventArgs(sNewStreet,

sNewCity, sNewState, sNewZipCode);

// raise the event with the updated arguments

AddressUpdated(this, args);

this.Dispose();

}

The second class contained in the code file is the �AddressUpdateEventArgs� class. This class is pretty straight forward; it contains a set of local member variables used to capture the address information collected from the form and some public read only properties used to access those values. The class constructor accepts all of the arguments necessary to populate the event argument properties. The code is as follows:

Collapse | Copy Code

public class AddressUpdateEventArgs : System.EventArgs

{

// add local member variables to hold text

private string mStreet;

private string mCity;

private string mState;

private string mZipCode;

// class constructor

public AddressUpdateEventArgs(string sStreet,

string sCity, string sState,

string sZip)

{

this.mStreet = sStreet;

Page 11: Pass Values From One User Control to Another User Control on a Web Page

this.mCity = sCity;

this.mState = sState;

this.mZipCode = sZip;

}

// Properties - Viewable by each listener

public string Street

{

get

{

return mStreet;

}

}

public string City

{

get

{

return mCity;

}

}

public string State

{

get

{

return mState;

}

}

public string ZipCode

{

get

{

return mZipCode;

}

}

}

Page 12: Pass Values From One User Control to Another User Control on a Web Page

Code: The ID Form

I am not going to describe the ID form as it is essentially the same as the Address form with the only exception being that it is used to capture the ID related information instead of the address information. The code for the ID form class is as follows:

Collapse | Copy Code

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

namespace PassBetweenForms

{

public partial class frmID : Form

{

// add a delegate

public delegate void IdentityUpdateHandler(

object sender, IdentityUpdateEventArgs e);

// add an event of the delegate type

public event IdentityUpdateHandler IdentityUpdated;

// default constructor

public frmID()

{

InitializeComponent();

}

// close the form without raising the event

private void btnCancel_Click(object sender,

EventArgs e)

{

this.Dispose();

}

// raise the event

private void btnOkay_Click(object sender,

Page 13: Pass Values From One User Control to Another User Control on a Web Page

EventArgs e)

{

// this button click event handler will raise

// the event which can then intercepted by any

// listeners

// read the textboxes and set the variables

string sNewFirst = txtFirstName.Text;

string sNewMiddle = txtMiddleName.Text;

string sNewLast = txtLastName.Text;

// instance the event args and pass it each

// value

IdentityUpdateEventArgs args =

newIdentityUpdateEventArgs(sNewFirst,

sNewMiddle, sNewLast);

// raise the event with the updated arguments

IdentityUpdated(this, args);

this.Dispose();

}

}

public class IdentityUpdateEventArgs : System.EventArgs

{

// add local member variable to hold text

private string mFirstName;

private string mMiddleName;

private string mLastName;

// class constructor

public IdentityUpdateEventArgs(string sFirstName,

string sMiddleName, string sLastName)

{

this.mFirstName = sFirstName;

this.mMiddleName = sMiddleName;

this.mLastName = sLastName;

}

// Properties - Accessible by the listener

Page 14: Pass Values From One User Control to Another User Control on a Web Page

public string FirstName

{

get

{

return mFirstName;

}

}

public string MiddleName

{

get

{

return mMiddleName;

}

}

public string LastName

{

get

{

return mLastName;

}

}

}

}

Code: Main Form.

The main form of the application is used to display the information originating from the ID and Address forms. The form contains a set of ID and a set of Address related text boxes that cannot be edited directly from the form. The form contains two buttons used to open an instance of either the Address or ID forms; information entered into those two forms is made available to the main form when the update event is fired from either of those forms.

The class is initialized with all of the default settings in terms of class library imports; the first part of the code is as follows:

Collapse | Copy Code

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

Page 15: Pass Values From One User Control to Another User Control on a Web Page

using System.Drawing;

using System.Text;

using System.Windows.Forms;

namespace PassBetweenForms

{

public partial class frmMain : Form

{

// default constructor

public frmMain()

{

InitializeComponent();

}

private void frmMain_Load(object sender,

EventArgs e)

{

// nothing to do

}

}

}

The first interesting bit of code in the main form is the button click event handler used to respond to a request to set the identity information; that code is as follows:

Collapse | Copy Code

private void btnSetName_Click(object sender, EventArgs e)

{

frmID f = newfrmID();

// Add an event handler to update this form

// when the ID form is updated (when

// IdentityUpdated fires).

f.IdentityUpdated += new frmID.IdentityUpdateHandler(

IdForm_ButtonClicked);

f.Show();

}

Page 16: Pass Values From One User Control to Another User Control on a Web Page

In this bit of code, a new instance of the ID form is created. Next, the event used to notify the listener that the ID information has been updated is associated with event handler contained in this, the main form class. After this association is defined, the form is displayed.

The main form event handler associated with the ID form event is as follows:

Collapse | Copy Code

// handles the event from frmId

private void IdForm_ButtonClicked(object sender,

IdentityUpdateEventArgs e)

{

// update the forms values from the event args

txtFirstName.Text = e.FirstName;

txtMiddleName.Text = e.MiddleName;

txtLastName.Text = e.LastName;

}

This handler accepts the custom event argument list passed when the event is raised and the values contained in the event arguments are used to update the form�s fields in response the event.

The next blocks of code are used to perform the same functions as the last two handlers only for the address information instead of the ID information:

Collapse | Copy Code

private void btnSetAddress_Click(object

sender, EventArgs e)

{

frmAddress f = newfrmAddress();

// Add an event handler to update this form

// when the Address form is updated (when

// AddressUpdated fires).

f.AddressUpdated += new frmAddress

.AddressUpdateHandler(AddressForm_ButtonClicked);

f.Show();

}

Page 17: Pass Values From One User Control to Another User Control on a Web Page

// handles the event from frmAddress

private void AddressForm_ButtonClicked(object sender,

AddressUpdateEventArgs e)

{

// update the forms values from the event args

txtStreet.Text = e.Street;

txtCity.Text = e.City;

txtState.Text = e.State;

txtZipCode.Text = e.ZipCode;

}

The last bit of code is merely a click event handler for the exit button:

Collapse | Copy Code

private void btnExit_Click(object sender, EventArgs e)

{

Application.Exit();

}

That concludes the description of all of the code used in this example.

Summary.

The article shows one approach to using events and delegates to pass data between forms through the use of custom event arguments. There are other ways to perform the same tasks but this is a convenient and easy approach to use. Delegates may be defined with different signatures and return types and for that reason is it possible to devise a number of alternative approaches to passing data between forms.

This example showed how the approach can be used to pass multiple values between forms simultaneously, however, one could use the same approach to pass a single value or values of different types just as easily.

Page 18: Pass Values From One User Control to Another User Control on a Web Page

There are many ways to pass data/Value from one form to another for example

1) using Constructor

2) using Properties

3) using Object

Here i am using delegates for transfer value/data from one form to another

example:

Form 1 code:

public delegate void del(TextBox textbox) ;

private void button1_Click(object sender,

EventArgs e)

{

Form2 obj =new Form2 ();

del d = new del(obj.loadValue);

d(this.textBox1);

obj.ShowDialog () ;

}

Page 19: Pass Values From One User Control to Another User Control on a Web Page

Form 2 code

public void loadValue(TextBox txt)

{

txtboxform2.Text = txt.Text;

}

Page 20: Pass Values From One User Control to Another User Control on a Web Page

Download demo project - 7 Kb Download source - 13 Kb

Introduction

This article will explain how to select a row on a Data Grid in one Windows Form, and populate controls in another Windows Form using a Delegate.The example in this article comes from trying to find a way to pass data between two separate forms  that were located in a custom plug-in I created.  Both forms did not have a parent form so to speak, that I could use to act as a bridge between the two. '

Background

Page 21: Pass Values From One User Control to Another User Control on a Web Page

There have been lots of articles describing what delegates are and how they are set up, I'll leave that to the reader and will just jump right into the code. '

Using the code

The code in this example consists of a Data Grid located in  FormBottom and a set of

controls located in FormTop .  By selecting a row from the Data Grid in

FormBottom you can automatically populate the controls in FormTop using a

Delegate.  Make sense? Continue reading.

In FormBottom.cs we define our delegate.

public delegate void CustomRowHandler( object sender, CustomRowEventArgs e);

and the event handler, which is defined as static.

public static event CustomRowHandler CustomRow;

The CustomRowEventArgs class.  The parameters passed are the DataSet ,

DataGrid and the Row selected.

public class CustomRowEventArgs : EventArgs { DataSet dataSet; DataGrid grid; int row; public CustomRowEventArgs( DataSet DSet,DataGrid Grid,int Row) { grid = Grid; row = Row; dataSet = DSet; } public DataSet DSet { get { return dataSet; } } public DataGrid Grid { get { return grid; } } public int Row

Page 22: Pass Values From One User Control to Another User Control on a Web Page

{ get { return row; } } }

We initialize the Data Grid when the form loads. See the project example code for more

information on BindFamousPeople() . DataGridTableStyle is used to

get the CurrentRowIndex of the DataGrid . We simply pass a

DataGridTableStyle to the DataGrid , which will then be used in the

MouseUp routine to get the current row.

private void FormBottom_Load( object sender, System.EventArgs e) { BindFamousPeople(); dgts = new DataGridTableStyle(); dgts.MappingName = "People"; dataGrid1.TableStyles.Add(dgts); }

We bind a MouseUp event to the Grid, and get the current row selected.  When a

MouseUp  event is fired, CustomRow  will pass the DataSet , DataGrid and

currentRowIndex to FormTop.cs.

public void dataGrid_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { int rowIndex = dgts.DataGrid.CurrentRowIndex; if (CustomRow != null) { CustomRow(this, new CustomRowEventArgs( dataSet1,dataGrid1,rowIndex)); }

In FormTop.cs we include the following code.  By use of a delegate, the

customHander_CustomRow function will be called when the mouseUp event is

triggered in FormBottom.cs.  See the mouseUp event above.

FormBottom.CustomRow += new DelegateExample.CustomRowHandler( customHandler_CustomRow);

Page 23: Pass Values From One User Control to Another User Control on a Web Page

The customHandler that does all the work in FormTop.cs.

private void customHandler_CustomRow(object sender, DelegateExample.CustomRowEventArgs e) { DataSet dSet = e.DSet; DataGrid grid = e.Grid; int row = e.Row; textBox2.Text = grid[e.Row,0].ToString(); textBox3.Text = grid[e.Row,1].ToString(); textBox4.Text = grid[e.Row,2].ToString(); }

Conclusion

That's it. I have kept the source code very simple so you should easily be able to see what is going on. The project files and source code for the article are provided above.