Design custom controls with events in ASP. NET

Source: Internet
Author: User

When trying to develop an application running on the network for the customer, I found that there were very few discussions about correct use of. NET Web controls. The following are FAQs about using. NET Web controls:

1. How can these controls communicate with each other?

2. How do I maintain these controls?

3. How can multiple controls be effectively connected to one web page?

I am an ASP developer and found that turning to ASP. NET is not a breeze. My initial thought was to maintain the state through the session object or using the query statement, but I found that these two methods are too messy, and, if you try to synchronize all Web controls on the web page, the problem may occur. I accidentally found an article about creating events in Web controls, but I still suffered a lot in practice. Therefore, I think it is very important to provide an instance for correctly creating Web controls and creating custom events at the same time.

The discussion will proceed in the following order:

1. Create a Web Control

2. Create custom events and event parameters for controls

3. Correctly Use Web controls on webpages

During the discussion, I will also provide readers with tips to develop applications more accurately and quickly.

The web control we created here is a custom drop-down box, which is based on the stores table in the standard SQL Server or MSDE pubs database. During development, we used Visual Studio. NET 2003 development tools and C # programming language.

After creating a pubs web project, the first task (at least for me) is to rename the webform1.aspx file to default. aspx and modify the class to match the name. Then, create a folder structure in the IDE environment to facilitate object search.

 

I will name the control storeselector. ascx. The first step is to add the dropdownlist control to the form.


(Figure 2)

Now it is time to "wiring" the control. Create a dataset Class Object:

# Code
Private dataset data;
# End code

Create the binddata function for entering data in the drop-down list:

# Code
Private void binddata ()
{
Data = new dataset ();
Sqlconnection CNN = new sqlconnection ("Data Source = (local); initial
Catalog = pubs; Integrated Security = sspi ");
Sqldataadapter adapter = new sqldataadapter ();
Adapter. selectcommand = new sqlcommand ("select stor_id, stor_name, stor_address, city, state, zip from stores", CNN );
Adapter. Fill (data, "stores ");
Storelist. datasource = data;
Storelist. datamember = "stores ";
Storelist. datatextfield = "stor_name ";
Storelist. databind ();
Session. Add ("data", data );
}
# End code

I added a DataSet object to the session variable so that the data can be accessed when the data is transmitted during the existence of the dialog and when the control event is triggered. Note: Make sure that the page_onload event is correct:

# Code
Private void page_load (Object sender, system. eventargs E)
{
If (! Page. ispostback)
{
Binddata ();
}
}
# End code

Now we drag the new control to the default. aspx webpage and run the project.


(Figure 3)


(Figure 4)

It's easy, right? The following is a relatively high skill part. We want to add several labels on default. aspx to reflect the changing store. We want each tag to display a column in the selected store. here we need to create a custom event for the storeselector control and event parameter class. Next we will first create event argument class (storeselectorcommandeventargs. CS ):

# Code
Public class storeselectorcommandeventargs
{
Private string _ stor_id;
Private string _ stor_name;
Private string _ stor_address;
Private string _ city;
Private string _ state;
Private string _ zip;

Public storeselectorcommandeventargs (string stor_id, string stor_name,
String stor_address, string city, string state, string zip)
{
_ Stor_id = stor_id;
_ Stor_name = stor_name;
_ Stor_address = stor_address;
_ City = city;
_ State = State;
_ Zip = zip;
}

Public String stor_id {get {return _ stor_id ;}}
Public String stor_name {get {return _ stor_name ;}}
Public String stor_address {get {return _ stor_address ;}}
Public String city {get {return _ city ;}}
Public String state {get {return _ state ;}}
Public String zip {get {return _ zip ;}}
}
# End code

The purpose of this class is to process the "e" variable that defines event parameters. All we have to do is create one of them. The following describes how to handle the event proxy class (storeselectorcommandeventhandler. CS ):

# Code
Public Delegate void storeselectorcommandeventhandler (Object sender,
Storeselectorcommandeventargs E );
# End code

The following is the generated file:


(Figure 5)
Now we can adjust the storeselector control to trigger the event.

The following code needs to be added to the storeselector control to execute the created event:

# Code
Public event storeselectorcommandeventhandler storeselectorchanged;
Protected virtual void onstoreselectorchanged (storeselectorcommandeventargs E)
{
If (storeselectorchanged! = NULL) storeselectorchanged (this, e );
}
# End code

Now we have defined an event for the control, and we need to trigger this event. We plan to trigger this event after the dropdownlist onchange event is triggered. Make sure that the autpostback attribute of the dropdownlist control is set to true.


(Figure 6)

The following is the event code:

# Code
Private void storelist_selectedindexchanged (Object sender, system. eventargs E)
{
Data = (Dataset) session ["data"];
Onstoreselectorchanged (
New storeselectorcommandeventargs
(Data. Tables ["stores"]. Rows [storelist. selectedindex]. itemarray [0]. tostring
(),
Data. Tables ["stores"]. Rows [storelist. selectedindex]. itemarray [1]. tostring (
),
Data. Tables ["stores"]. Rows [storelist. selectedindex]. itemarray [2]. tostring (),
Data. Tables ["stores"]. Rows [storelist. selectedindex]. itemarray [3]. tostring (),
Data. Tables ["stores"]. Rows [storelist. selectedindex]. itemarray [4]. tostring (),
Data. Tables ["stores"]. Rows [storelist. selectedindex]. itemarray [5]. tostring (
)));
}
# End code

Let's analyze what we have done here. When the selectedindexchanged event is triggered, I pass it to the new event created for the control. The data I transfer is directly related to the filled dataset, and all entries are passed to the storeselectorcommandeventargs object one by one, then the event is triggered.
To access the new features of the default. aspx webpage, we need to add the event handler in the oninit section of this class:


(Figure 7)

As shown in, the storeselectorchanged event appears on the default. aspx webpage. Next we will give it a function. I will add six labels on the default. aspx webpage, And the displayed values will change with dropdownlist:


(Figure 8)

Now let's write events.

Appearance: intelliisense is the principle that intelliisense recognizes custom eventarg class attributes:


(Figure 9)

The final event functions are as follows:

# Code
Private void storeselector1_storeselectorchanged (Object
Sender, pubs. Controls. storeselectorcommandeventargs E)
{
Label1.text = E. stor_id;
Label2.text = E. stor_name;
Label3.text = E. stor_address;
Label4.text = E. City;
Label5.text = E. State;
Label6.text = e.zip;
}
# End code

Now we will test the project. As soon as the webpage is loaded, the reader may feel like this in his mind: it has a problem, but I promise you that there is no problem with this project. If you want to trigger this event when a webpage is loaded, you must set the index attribute selected in the dropdownlist control in the created control.


(Figure 10)

As long as we select another store from dropdownlist, the tag will change:


(Figure 11)

Now we load the form to the first record. We add the following attributes on the storeselector control:

# Code
Public int selectedindex
{
Get {return storelist. selectedindex ;}
Set
{
If (! Page. ispostback)
{
Binddata ();
}
If (value <storelist. Items. Count)
{
Storelist. selectedindex = value;
Onstoreselectorchanged (
New storeselectorcommandeventargs
(Data. Tables ["stores"]. Rows [value]. itemarray [0]. tostring (),
Data. Tables ["stores"]. Rows [value]. itemarray [1]. tostring (),
Data. Tables ["stores"]. Rows [value]. itemarray [2]. tostring (),
Data. Tables ["stores"]. Rows [value]. itemarray [3]. tostring (),
Data. Tables ["stores"]. Rows [value]. itemarray [4]. tostring (),
Data. Tables ["stores"]. Rows [value]. itemarray [5]. tostring ()));
}
}
}
# End code

Set the attributes of the page_load event in default. aspx:

# Code
Private void page_load (Object sender, system. eventargs E)
{
// The user initializes the webpage code
If (! Page. ispostback)
{
Storeselector1.selectedindex = 0;
}
}
# End code

When running the project, it loads the form to the first record.

Summary

I hope this article will help readers. There are almost no restrictions on the development of such Web applications. As long as the design is proper, every web control we create can be used in the entire web application.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.