"You cannot select multiple items in the DropDownList. "Its solutions and additions

Source: Internet
Author: User
Tags opening and closing tags

Explore C #. NET under DropDownList's an interestingBugs and their solutions

Summary:

In this paper, the SelectedIndex properties of the DropDownList control used in web development in c#.net environment are discussed in detail, and the problems existing in the use of this attribute are found, and the methods of avoidance and solution are put forward after testing.

Keywords:

Dropdownlist,selectedindex, trace Debug, c#.net

Probe into A Bug of DropDownList in c#.net And the resolvent

Abstract:

This article has discussed the attribute-selectedindex of DropDownList Control,which is frequently used in the Developmen T environment of C#.net. By tracing the program in Detail,find out the reason of this bug. Give out the scheme of what to avoid of and resolvent it.

Keywords:

DropDownList, SelectedIndex, Debug, Trace into, c#.net

1. Introduction

The development of information and networks makes Web-based applications more and more popular with VS. NET is undoubtedly one of the most appropriate tools for developing Web application systems. But we found in the long-term development practice that C #. NET DropDownList control in the use of the process will encounter some problems, its SelectedIndex property has a read-write flaw, this problem has been plagued by other developers. Therefore, this article has done the detailed test to the DropDownList, explores the problem and the solution.

2. DropDownList Control Introduction

DropDownList is a control under the C#.net Control Panel Web form, and its namespace is System.Web.UI.WebControls.DropDownList. It is a control that allows the user to select an item from a drop-down list by placing a ListItem object for each item between the opening and closing tags of the DropDownList control, specifying the items that you want to appear in the DropDownList control, and also supporting data binding. DropDownList's functionality determines its usefulness in daily development, which is second only to textbox in data-entry controls. By pre-setting or dynamic Data binding to fill in the data available to the user, it is convenient for users to operate, enhance the ease of use of the software, but also to effectively standardize the data input, the software developer is one of the most frequently selected controls.

3. Interesting questions about SelectedIndex

In the long-term use of the process we found that when the DropDownList list in the program dynamically selected,

Or specify SelectedIndex as a value, an unexpected error occurs. It is difficult to find the problem by using breakpoints to track the Debug method or to read the SelectedIndex value to a variable for testing.

3.1 Problems found

Suppose you have the following simple code

private void Page_Load (object sender, System.EventArgs e)

{

if (! IsPostBack)

{//Initialize DropDownList drop-down list

Init_filllist ();

}

}

private void Btnok_click (object sender, System.EventArgs e)

{

String Strid=txtcontinentid.text.trim ();

Select the specified item

ListContinent.Items.FindByValue (Strid). Selected=true;

Response.Write ("ok!");

}

#region初始化下拉列表方法

private void Init_filllist ()

{//Define ListItem Object

ListItem item;

Clear List

ListContinent.Items.Clear ();

Write List

ListContinent.Items.Add ("");

Item=new ListItem ("Asian", "Asia");

LISTCONTINENT.ITEMS.ADD (item);

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

LISTCONTINENT.ITEMS.ADD (item);

Item=new ListItem ("Americas", "Amer");

LISTCONTINENT.ITEMS.ADD (item);

}

#endregion

Put it in a simple Web page to run directly, enter the continent number Asia,euro in the input box, any of the Amer, click the Btnok button, the code appears to have no problem, reported the following vs.net famous error Yellow Pages: (remember: Error a)

DropDownList cannot have more than one item selected.

Description: An unhandled exception occurred during the execution of the current WEB request. Check the stack trace information For more information about the error and the source of the error in your code. Exception Details: System.Web.HttpException:DropDownList cannot have more than one item selected.

By carefully verifying the code and querying the online help, it is found that the use of DropDownList is consistent with the use of the relevant documentation, without any problems. In order to track the cause of the lookup error, all code outside of the Btnok_click () event is try...catch protected for debugging, stepping, and discovery is performed until Response.Write ("ok!") Sentence, the program did not jump, continue down, at this time the event has been executed, no errors, should show normal Web page, at this point, the above error yellow pages appear again. Debugging can not find the error, how to solve this problem, is the development of the tool, so think of the following methods. 3.2 Issues Temporary resolution cannot have multiple items selected, possibly because DropDownList cannot automatically remove the original selection until the new item is selected, that is, the list that has been added to the data cannot be initialized effectively. Then after each postback the DropDownList data re-binding refresh to the system's own default values, and then make a new selection of items, the code under the Page_Load () event is adjusted as follows

private void Page_Load (object sender, System.EventArgs e)

{

Remove if (! IsPostBack) rewrite data every time

Init_filllist ();

Run the program again at this time, no more error A, it is working. However, the Web application is different from the application of the system in the LAN, it is more efficient to execute the program, so as to minimize the access to the server. If a page re-accesses the server initialization data session each time it refreshes, it can seriously increase the burden on the server. Once the volume of data is large or the number of access terminals increases, the page display becomes very slow and the customer cannot tolerate it. Other solutions need to be pursued. 3.3 Interesting bug because in the past has long been engaged in the development of Delphi application System, the use of Combox control is very familiar with, because their function is basically the same, infer that its use should also be some of the same, so the Txtok_click () modified, to Txtok2_ Click () Event:

private void Txtok2_click (object sender, System.EventArgs e)

{

String Strid=txtcontinentid.text.trim ();

this.listcontinent.selectedindex=-1;//New Add Line

ListContinent.Items.FindByValue (Strid). Selected=true;

Response.Write ("ok!");

} Run the program, sure enough, in addition to IsPostBack judgment, the program can still run normally. However, this is not consistent with the MSDN online Help for DropDownList usage instructions. The related Property Description: "Dropdownlist.selectedindex property, the index of the selected item in the DropDownList control. The default value is 0, which selects the first item in the list. Note Use the SelectedIndex property to programmatically specify or determine the index of the selected item in the DropDownList control. Always select an item in the DropDownList control. You cannot deselect all items in the list at the same time. Note The zero-based index of the item in the DropDownList control. Interestingly, a program that does not conform to the rules of use does not report any errors, but makes the program work properly. In order to see if the actual value of SelectedIndex at run time is 0 or 1 or another value, trace the debugs again, and an interesting bug has been found at this point. Set the breakpoint to the This.listcontinent.selectedindex=-1 line, and when the program runs here, move the mouse to the SelectedIndex position, view its value (or view it from the variable viewer below the development environment), and discover that the value is 0 at this point, Continue running down, error a appears again. In the same debug state, stepping through the code, just do not look at the SelectedIndex operation (through the variable viewer is not possible), until the trace is complete, the program runs no problem. Obviously, this is C #. NET is a bug. 3.4 In a different value mode since you cannot view the value of a variable at debug time through the system's return value, you can only make a change by customizing the variable to get the value of SelectedIndex. The Txtok2_click () is then modified to Txtok3_click () event:

private void Btnok3_click (object sender, System.EventArgs e)

{

Know i=0 after new line debugging

int i= Listcontinent.selectedindex;

String Strid=txtcontinentid.text.trim ();

This.listcontinent.selectedindex=-1;

Know j=0 after new line debugging

int j=this.listcontinent.selectedindex;

ListContinent.Items.FindByValue (Strid). Selected=true;

Response.Write ("ok!");

}

Run the program, the real problem arises, whether in the debug state or non-debug state, is the same "DropDownList cannot have multiple items selected" error. This means that the value of SelectedIndex cannot be viewed or read at all, which is further proof of C #. NET in the SelectedIndex read implementation code is problematic, there is an unsafe judgment.

In addition, after the debugging observation I and J return value is the same result, this result and the system specified selectedindex default value of 0 consistent. This proves that this.listcontinent.selectedindex=-1 this line of code does not work in Txtok2_click (), but adding that line of code solves the problem and causes the program to run properly.

3.5 Source of the problem

Through the Anti-compilation tool and the. NET source help, found in C #. NET in the DropDownList of the source code implementation, found the root cause of the problem. The following is C #. NET DropDownList of the SelectedIndex attribute source code implementation:

[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;       }}

The implementation of the source code shows that, when taking SelectedIndex automatically judged, as long as there is data so selected value is certainly greater than or equal to 0, so we found in the view set to 1 is invalid, it will automatically change to 0. In addition it did another operation of this. Items[0]. Selected = True, this is the cause of the direct cause of exception (developers just want to see selectedindex it will item[0] Selected value to change ...), so when debugging the program should be careful to avoid this problem, We can only modify the code to make the program work properly, but not to change VS. NET of source code implementation.

Figure one is the program test interface, the implementation of BTNOK,BTNOK2,BTNOK3 and list data binding code is given above.

4. Conclusion

After debugging, there is also the problem of "error a" in the case of initial setup selectedindex=0. And if you change the selectedindex=-1 in 3.3 to selectedindex=0, this scenario will also cause "error a" If the program does not debug.

In the system is not high efficiency requirements, the data volume is small, you can use a 3.2 approach to avoid this problem, that is, each time the page is loaded to reinitialize the DropDownList list. You can also improve this by taking the method of setting SelectedIndex to-1 in 3.3, but do not make single-line debugging on the Selectedindex=-1 line at this time. Both methods do not have any program errors due to SelectedIndex when the project is delivered.

This article writes debugging in the Microsoft. NET Framework 1.1, C #. NET 2003 version 7.1,ie6.0 environment.

Resources

[1]. [US] g.andrew Duthie, ASP. NET Programming "[M], Tsinghua University Press, 2002.7

[2]. Chapter Lin Yu, ASP. NET program design [M], Tsinghua University Press, 2001.6


Add:

The above problem can be solved by using the ClearSelection () method of list.
I had the same problem but, after all the above methods have been tried, it will not work.
I've added a new line every time I bind the data,
So I think the relationship between ListItem and DropDownList is similar to the relationship between the DataRow and the DataTable?
Found the answer at the following URL
http://gamtindev.spaces.live.com/blog/cns!E6E0862AFE090F4B!126.entry?wa=wsignin1.0

"You cannot select multiple items in the DropDownList. "Its solutions and additions

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.