Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of bug in C # DropDownList

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to solve the bug of C # DropDownList". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "how to solve the bug of C # DropDownList"!

1. Introduction

With the development of information and network, the system based on Web application is becoming more and more popular. VS.Net is undoubtedly one of the most suitable tools to develop Web application system. However, in our long-term development practice, we have found that there are some problems in the use of DropDownList controls under C#.Net, and there is a read-write defect in its SelectedIndex property, which has always perplexed other developers. Therefore, this paper makes a detailed test of DropDownList to explore the problem and solution.

Introduction of 2.C# DropDownList Control

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 the drop-down list. By placing a ListItem object for each item between the opening and closing tags of the C # ropDownList control, you can specify the items you want to display in the C # DropDownList control and also support data binding. The function of DropDownList determines its practicability in daily development, and its utilization rate is second only to TextBox in data entry controls. Filling it into the data that can be selected by users through pre-setting or dynamic data binding not only facilitates the operation of the user, enhances the ease of use of the software, but also effectively standardizes data input, and becomes one of the most common controls selected by software developers.

3. Interesting questions about SelectedIndex

In the course of long-term use, we have found that when an item in the DropDownList list is dynamically selected in the program

Or when you specify SelectedIndex to a certain value, an unexpected error occurs. However, it is difficult to find the problem by using the breakpoint tracking debugging method or reading the SelectedIndex value to a variable for testing.

3.1 Discover problems

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 initialize the drop-down list method private void Init_FillList () {/ / define the ListItem object ListItem item / / clear 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 into a simple web page and run it directly, enter the continent number Asia,Euro, any one of Amer in the input box, click the btnOK button, and there seems to be no problem with the code, reporting the following VS.Net famous error yellow pages: (marked: error A)

C# 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 in the code that caused the error. Exception details: System.Web.HttpException: DropDownList cannot have more than one item selected.

By carefully checking the code and querying the online help, it is found that the use of DropDownList is in line with the use of the relevant documentation, without any problems.

To track and find the cause of the error, add try around all the code under the btnOK_Click () event. Catch protection is debugged, step by step, and found to be executed until Response.Write ("OK!") Sentence, the program did not jump out, continue down, at this time the event has been executed, no errors, should show a normal web page, just at this time, the above error yellow page appeared again. Debugging can not find the error, how to solve this problem, is it the reason for the development tool, so think of the following ways.

This may be due to the fact that DropDownList cannot automatically remove the original selection before selecting a new item, that is, it cannot effectively initialize the list of added data. So after each PostBack, the data rebinding refresh of DropDownList is restored to the default value set by the system itself, and then the new item is selected, and 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 Init_FillList () every time;}

When you run the program at this time, error A no longer occurs and runs normally. However, the web application is different from the application of the system in the local area network, it requires higher program execution efficiency and should minimize the access to the server. If a page has to revisit the server initialization data each time it is refreshed, it will seriously increase the burden on the server. Once the amount of data is large or the number of terminals accessed is increased, the display of the page will become very slow and the customer can't stand it. We need to continue to look for other solutions.

Interesting bug has been engaged in the development of application systems under Delphi for a long time in the past, and is very familiar with the use of Combox controls. Since their functions are basically the same, it is inferred that their usage methods should also be somewhat similar, so modify txtOK_Click () to get the txtOK2_Click () event:

Private void txtOK2_Click (object sender, System.EventArgs e) {string strID=txtContinentID.Text.Trim (); this.listContinent.SelectedIndex=-1;// new line listContinent.Items.FindByValue (strID) .Selected = true; Response.Write ("OK!");}

Running the program, sure enough in the case of IsPostBack judgment, the program can still run normally. However, this is not consistent with the instructions for using DropDownList in the msdn online help. Related property description: "DropDownList.SelectedIndex property, the index of the selected item in the DropDownList control. The default value is 0, which selects the * item in the list. Note use the SelectedIndex property to programmatically specify or determine the index of the selected item in the DropDownList control. One item is always selected in the DropDownList control. You cannot deselect all items in the list at the same time. Note that the index of items in the DropDownList control starts from zero." What is interesting is that the program that does not comply with the usage regulations does not report any errors, but makes the program run normally.

To see if the actual value of SelectedIndex at run time is 0 or 1 or something else, trace the debug again and find an interesting bug. Set the breakpoint to the this.listContinent.SelectedIndex=-1 line, and when the program runs here, move the mouse over the SelectedIndex to see its value (or through the variable viewer under the development environment), and find that the value at this time is 0, continue to run down, and error An occurs again. And the same debug state, step into the code, but do not check the SelectedIndex operation (not through the variable viewer), until the trace is complete, the program runs without problems. Obviously, this is a bug of C#.Net.

Since you can't check the value of the variable through the return value prompt of the system during debugging, you can only modify it and get the value of SelectedIndex by defining your own variables. So modify txtOK2_Click () to get the txtOK3_Click () event:

Private void btnOK3_Click (object sender, System.EventArgs e) {/ / the new line is debugged to know that iExten0 int I = listContinent.SelectedIndex; string strID=txtContinentID.Text.Trim (); this.listContinent.SelectedIndex=-1; / / the new line is debugged to know int junithis.listContinent.SelectedIndex; listContinent.Items.FindByValue (strID) .Selected = true; Response.Write ("OK!");}

When you run the program, the real problem arises, whether in debug or non-debug state, it is the same "DropDownList cannot have multiple items selected" error. This shows that the value of SelectedIndex can not be viewed or read at all, which further proves that there is a problem with the reading implementation code of SelectedIndex in C#.Net and that there is an unsafe judgment.

In addition, after debugging at this time, it is observed that the return values of I and j are the same, which is also consistent with the default value of 0 for SelectedIndex. This proves that the line of this.listContinent.SelectedIndex=-1 is useless and useless in txtOK2_Click (), but adding this line of code can solve the problem and make the program work properly.

3.5 the source of the problem

With the help of decompiler and. Net source code, the source code implementation of DropDownList in C#.Net is found, and the root of this problem is found. The following is the SelectedIndex attribute source code implementation 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 when taking SelectedIndex, it is automatically judged that as long as there is data, then the value of Selected must be greater than or equal to 0, so when we check it, we find that setting to-1 is invalid, it will be automatically changed to 0. In addition, it also made another operation this.Items [0] .Selected = true, which is the direct cause of Exception (developers just want to see SelectedIndex it changed the selected value of Item [0].), so we should pay attention to avoid this problem when debugging the program, we can only modify the code to make the program run normally, but not change the source code of VS.NET.

The implementation of the program test interface, btnOK,btnOK2,btnOK3 and list data binding code is given above.

At this point, I believe you have a deeper understanding of "how to solve the bug of C # DropDownList". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

  • How to realize simple package pop-up window by WeChat Mini Programs

    Today, I would like to talk to you about how WeChat Mini Programs realizes the simple packaging pop-up window, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following contents for you. I hope you can gain something according to this article. 1. Create component folder 2. Write component content

    © 2024 shulou.com SLNews company. All rights reserved.

    12
    Report