简体   繁体   中英

ASP.NET: Remove specific item in Dropdownlist

I'm doing a code for Time Start and Time End. So I did is manual coding.

Here's my example gui:

its HH:MM

在此输入图像描述

Value for Hour is From 00 - 23 then for the Minutes is From 00 - 59

Scenario:

My Start Time will be 8:00 [8-Hour,00-Minutes], its also have an autopostback. So for the End Time of Hour it will not display the 00-07 for the Hour it will display only the number 8 to 23.

Here's my code:

int _intDiff = _tmrStart - _tmrEnd;

for (int x = 0; x <= _intDiff; x++)
{  
  DropDownList3.Items.Remove(DropDownList3.Items[x]);
}

Its working but its displaying wrong output..

Here's the example output:

在此输入图像描述

As you can see there, the program removes only the even number 00,02,04,06,08. How can I make that Staring from 00 - 07 will be remove in the dropdownlist?

你可以使用方法

DropDownList3.Items.Remove(DropDownList3.Items.FindByValue("02"));

If you iterate through forwards then the first element is removed on the first iteration which is 00. On the second iteration the second element is removed, which is no 02 as 01 has moved up to the first element. You need to iterate backwards so that the elements are removed from the last one to the first. Try:

for (int x = _intDiff -1; x > -1; x--)
{  
  DropDownList3.Items.Remove(DropDownList3.Items[x]);
}

The code above assumes the index and value are always the same, which is not true as soon as one of the items is removed. LINQ makes this simple.

//DropDownList3.Items.Remove(DropDownList3.Items[x]);

var item = DropDownList3.Items.Select(p=>p.value == userSelectedValue).first();
DropDownList3.Remove(item);

In code above all you need to do is get the value they selected and put it in the userSelectedValue parm.

you are removing indexes, not valuse.. therefore when you loop and remove 1,2,3,4,5,6,7
your values change their index

eg
idx, val
0, 1
1, 2
2, 3
3, 4
4, 5
5, 6
6, 7

remove 0
0,2
1,3
2,4
...
...

remove 1
0,2 1,4
2,5
3,6

and so on...

simplest solution: remove the items backwards :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM