Princess Toledo
Princess Toledo

Reputation: 81

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

enter image description here

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:

enter image description here

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?

Upvotes: 2

Views: 20085

Answers (4)

Behruz Tolibov
Behruz Tolibov

Reputation: 455

You can use method

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

Upvotes: 3

JWP
JWP

Reputation: 6963

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.

Upvotes: 1

Tomer W
Tomer W

Reputation: 3443

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

e.g.
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 :)

Upvotes: -1

Coding Flow
Coding Flow

Reputation: 21881

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]);
}

Upvotes: 2

Related Questions