Exploring an interesting bug in dropdownlist under C #. NET and Its Solution

Source: Internet
Author: User

Abstract:

C #. the selectedindex attribute of the dropdownlist control, which is frequently used in Web development in the. NET environment, is discussed in detail, and the problems existing in the use of this property are found. After testing, proposed methods to avoid and solve the problem.

Keywords:

Dropdownlist, selectedindex, tracing debugging, C #. net

Probe into a bugDropdownlist inC #. netAnd the resolvent

 

Abstract:

This article have discussed the attribute-selectedindex of dropdownlist control, which is frequently used in the development environment of C #. net. by tracing the program in detail, find out the reason of this bug. give out the scheme of how to avoid of and resolvent it.

Keywords:

Dropdownlist, selectedindex, debug, trace into, C #. net

1. Introduction

With the development of information and networks, web application-based systems are becoming increasingly popular. vs. NET is undoubtedly one of the most suitable tools for developing web application systems. However, in our long-term development practices, we found that C #. net dropdownlist control may encounter some problems during use. Its selectedindex attribute has a read/write defect, which has been plagued by other developers. Therefore, this article specifically tests dropdownlist to find out the problem and solution.

2. Introduction to the dropdownlist Control

Dropdownlist is a control in the web form of the C #. Net Control Panel. Its namespace is system. Web. UI. webcontrols. dropdownlist. It is a control that allows users to select an item from the drop-down list. By placing a listitem object for each item between the start and end mark of the dropdownlist control, you can specify the items you want to display in the dropdownlist control, and also support data binding. The dropdownlist function determines its practicality in daily development. In the data input control, its usage is second only to textbox. By pre-setting or dynamic data binding, you can enter data that can be selected by users, which facilitates user operations, enhances the ease of use of software, and effectively standardizes data input, become one of the most commonly selected controls for software developers.

3. Interesting questions about selectedindex

During long-term use, we found that when a certain item in the dropdownlist is dynamically selected in the program,

An unexpected error occurs when selectedindex is specified as a value. However, it is difficult to locate the problem by using the breakpoint tracking debugging method or reading the selectedindex value to a variable for testing.

3.1 discover problems

The following simple code is provided:

Private void page_load (Object sender, system. eventargs E)

{

If (! Ispostback)

{// Initialize the dropdownlist drop-down list

Init_filllist ();

}

}

Private void btnok_click (Object sender, system. eventargs E)

{

String Strid = txtcontinentid. Text. Trim ();

// Select a specified item

Listcontinent. Items. findbyvalue (Strid). Selected = true;

Response. Write ("OK! ");

}

# Region initialization drop-down list method

Private void init_filllist ()

{// Define the listitem object

Listitem item;

// Clear the list

Listcontinent. Items. Clear ();

// Write list

Listcontinent. Items. Add ("");

Item = new listitem ("Asia", "Asia ");

Listcontinent. Items. Add (item );

Item = new listitem ("Europe", "Euro ");

Listcontinent. Items. Add (item );

Item = new listitem ("America", "Amer ");

Listcontinent. Items. Add (item );

}

# Endregion

Put it on a simple web page and run it directly. In the input box, enter the continent number Asia, euro, or Amer, and click the btnok button. It seems that there is no problem with the code, the following vs is reported. net famous Yellow Pages: (marked as error)

Dropdownlist cannot have multiple items selected.

Note: An unhandled exception occurs during the execution of the current Web request. Check the stack trace information for details about the error and the source of the error in the code. Exception details: system. Web. httpexception: multiple items cannot be selected in dropdownlist.

By carefully checking the code and querying the online help, we can find that dropdownlist is applicable
There are no problems with the usage of this document.
 

 
To track the cause of the error, add
Try... Debug catch protection and perform it in one step.
To response. Write ("OK! "), The program did not jump out, continue down, this event has
The execution is complete and there are no errors. A normal web page should be displayed.
The yellow pages appear again. The error cannot be found during debugging. How can this problem be solved,
Is it the reason for developing tools, so think of the following methods.
 

 
3.2 solve the problem temporarily
Multiple items cannot be selected, probably because dropdownlist cannot automatically remove the original
You Cannot initialize the list of added data effectively. So after each PostBack request
Rebind and refresh the dropdownlist data to the default value specified by the system, and then
Select a new item and adjust the code under the page_load () event as follows:
 

 

Private void page_load (Object sender, system. eventargs E)

{

// Remove if (! Ispostback) rewrite data every time

Init_filllist ();

         }
Run the program again. Error A is no longer displayed and the program runs normally.
However, unlike LAN systems, web applications require higher program execution efficiency,
Minimize access to the server. If a page needs to be refreshed every time
Accessing the server's initial data location will seriously increase the burden on the server. Once the data volume is large
Or the increase in the number of terminals to access will slow the page display and the customer will not be able to bear it.
Other solutions need to be sought.
 

 
3.3 interesting bugs
Since I used to develop Delphi application systems for a long time
They are very familiar with usage. Since their functions are basically the same, it is inferred that their usage should also be
Similarly, you can modify txtok_click () to obtain the txtok2_click () event:
 

 

Private void txtok2_click (Object sender, system. eventargs E)

{

String Strid = txtcontinentid. Text. Trim ();

This. listcontinent. selectedindex =-1; // Add a new row

Listcontinent. Items. findbyvalue (Strid). Selected = true;

Response. Write ("OK! ");

         }
Run the program. When the ispostback clause is used, the program can still run normally.
However, this is inconsistent with the usage instructions of the msdn online help for dropdownlist.
Related attributes: "dropdownlist. selectedindex attributes,
The index of the selected item in the dropdownlist control. The default value is 0.
Item 1. Remarks use the selectedindex attribute to specify or determine programmatically
The index of the selected item in the dropdownlist control. The dropdownlist Control always selects one item.
You cannot deselect all items in the list. Note
The index starts from scratch ". Interestingly, no errors are reported for programs that do not comply with the usage rules,
Instead, the program runs normally.
 

 
To check whether the actual value of selectedindex is 0 or 1 or another value at runtime, trace again
Debugging: An interesting bug was found. Set the breakpoint
This. listcontinent. selectedindex =-1 line. When the program runs here, move the cursor
The position of selectedindex to view its value (or through the variables under the development environment)
View in the viewer). It is found that the value is 0 at this time and continues to run downward. Error A appears again.
The same is the debugging status. The code is executed in one step, but the selectedindex operation is not performed.
(It cannot be viewed through the variable viewer). The program runs normally until the tracking is completed.
Obviously, this is a bug in C #. net.
 

 
3.4 change the Value Method
Since you cannot view the variable value through the system return value prompt during debugging, you can only change it,
You can define variables to obtain the value of selectedindex. Therefore, txtok2_click ()
To modify the TXT tok3_click () event:
 

 

Private void btnok3_click (Object sender, system. eventargs E)

{

// I = 0 after debugging the newly added line

Int I = listcontinent. selectedindex;

String Strid = txtcontinentid. Text. Trim ();

This. listcontinent. selectedindex =-1;

// Know J = 0 after the new addition line is debugged

Int J = This. listcontinent. selectedindex;

Listcontinent. Items. findbyvalue (Strid). Selected = true;

Response. Write ("OK! ");

}

The real problem occurs when running the program. Whether in debug or non-Debug status, the error "dropdownlist cannot have multiple items selected" is the same. This indicates that the value of selectedindex cannot be viewed or read at all. This further proves that the read implementation code of selectedindex in C #. NET is faulty and insecure.

In addition, after debugging at this time, it is observed that the return values of I and j are the same, and this result is also consistent with the default value of selectedindex set by the system. This proves that this. listcontinent. selectedindex =-1 line of code is useless in txtok2_click (). However, this line of code can solve the problem and make the program run normally.

3.5 Root Cause

With the help of the decompilation tool and. net source code, we found the source code implementation of dropdownlist in C #. NET and found the root cause of this problem. The following is the source code implementation of the selectedindex attribute of dropdownlist in C #. Net:

[WebCategory("Behavior"),DesignerSerializationVisibility(
DesignerSerializationVisibility.Hidden),DefaultValue(0),WebSysDescription(
"Dropdownlist_selectedindex")]
 

 
public override int SelectedIndex
{
      get
      {
            int num1 = base.SelectedIndex;
            if ((num1 < 0) && (this.Items.Count > 0))
           {
                  this.Items[0].Selected = true;
                  num1 = 0;
            }
            return num1;
      }
      set
      {
            base.SelectedIndex = value;
      }
}

This source code implementation shows that the selectedindex is automatically judged. As long as there is data, the value of selected must be greater than or equal to 0, therefore, we found that setting-1 is invalid and it will be automatically changed to 0. In addition, it also performs another operation this. items [0]. selected = true, which is the cause of exception (the developer just wants to see selectedindex and it will change the selected value of item [0 ...), therefore, you should avoid this problem when debugging the program. We can only modify the code to make the program run normally, but cannot change. net source code implementation.

Figure 1 shows the program test interface. The implementation of btnok, btnok2, btnok3, and list data binding code is shown above.

4. Conclusion

After debugging, the problem of "error a" also exists when selectedindex = 0 is initially set. In addition, if selectedindex =-1 in 3.3 is changed to selectedindex = 0, "error a" will also occur if the program is not debugged and running ".

When the system does not require high efficiency and a small amount of data, you can avoid this problem by 3.2. That is, you can reinitialize the dropdownlist every time you load the page. You can also use the method of setting selectedindex to-1 in 3.3 to improve this problem, but do not perform single-Line Debugging on the selectedindex =-1 line at this time. The two methods do not have any program errors caused by selectedindex when the project is delivered and run.

All tests are compiled and debugged in Microsoft. NET Framework 1.1, C #. NET 2003 version 7.1, and ie6.0.
Related Article

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.