0

I am beginner to the dot.net, can any one suggest me how to remove specific value in fetched dropdown list.

Here why I am mentioning fetched means that dropdownlist is generated from or fetched from a table using sql.

sqlquery=SELECT DISTINCT rtrim(ltrim(C.Cust_name)) as Cust_name FROM table1 A inner join table2 B on A.cust_code = B.Cust_Code
SqlCommand cmd = new SqlCommand(sqlquery, conn);
            SqlDataReader sr = cmd.ExecuteReader();

        while (sr.Read())
        {
            {
                cmb_cust.Items.Add(sr["Cust_name"].ToString());
            }
        }

foreach (ListItem li in cmb_cust.Items)
            {
              {
                    if (li.Value == "value1")
                        cmb_cust.Items.Remove(li);
                }
            }

If I process the above statement I facing collection was modified enumeration operation may not execute, can I get the any other solution like swaping the list to temp list and process the operation. I don`t need the value1 after fetching from the sql.

Nachiappan R
  • 182
  • 1
  • 1
  • 20

3 Answers3

2

Even better than removing the item afterwards, don't add it in the first place.

while (sr.Read())
{
    var txt = sr["Cust_name"].ToString();
    if (txt != "value1")
       cmb_cust.Items.Add(txt);
}

Or you can exclude it already in the SQL query.

SELECT tbl1.Cust_name 
FROM
(
  SELECT DISTINCT rtrim(ltrim(C.Cust_name)) as Cust_name 
  FROM table1 A 
  inner join table2 B on A.cust_code = B.Cust_Code
) As tbl1
where 
tbl1.Cust_name != 'value1'

The reason you are getting that exception is that you can not remove items from a collection while it is being enumerated. If you want to remove an item you should write:

cmb_cust.Items.Remove("value1");
Magnus
  • 45,362
  • 8
  • 80
  • 118
1

Even better than skipping it in the adding process is not to fetch it from the DB at all:

sqlquery = @"SELECT DISTINCT rtrim(ltrim(C.Cust_name)) as Cust_name 
 FROM table1 A inner join table2 B on A.cust_code = B.Cust_Code 
 WHERE Cust_name <> 'value1'";

;-)

LocEngineer
  • 2,847
  • 1
  • 16
  • 28
0

You can't modify the collection with foreach loop. Change it to for loop and that should work.

Sami
  • 2,050
  • 1
  • 13
  • 25
  • Thanks I will try to use and get back to you – Nachiappan R May 15 '15 at 14:18
  • Point is, you do not need to loop through the items **at all** in order to delete a specific entry. Just use **cmb_cust.Items.Remove("value1");** directly and Bob's your uncle. – LocEngineer May 15 '15 at 14:21
  • @LocEngineer That's true. Pointing out the correct way to iterate for future reference in case iterating and modifying is necessary for another reason. – Sami May 15 '15 at 14:40