Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

asp.net C# best practices for setting selected items in listbox

Posted on 2015-02-05
1
Medium Priority
?
304 Views
Last Modified: 2015-03-04
experts,

I'm currently setting the selected items of listitems in my list box from a sql database using this loop:

 while (rdr.Read())
{
    foreach (ListItem item in myList.Items)
    {
        if (rdr["CODE"].ToString() == item.Value.ToString())
            item.Selected = true;
    }
}

I'm pretty sure this isn't the most efficient method. Can anyone give me an example of the best way to set my selected items in a listbox from a dataset.

Thanks in advance
0
Comment
Question by:telliot79
1 Comment
 
LVL 17

Accepted Solution

by:
OriNetworks earned 2000 total points
ID: 40591271
For this purpose I created a reusable utility function that works like this:
This is not actual code, only pseudo code
function SetSelectedByValue(DropDownList ddl, String valueToSelect, String textOfItem(optional), Boolean InsertIfNotExists )
{
//make sure any currently selected item is unselected
if ddl.SelectedItem is nothing Then
{
ddl.SelectedItem.selected = false
}

if (ddl.Items.FindByValue(LookupValue) !=null) 
{
//if found then select it
ddl.Items.FindByValue(LookupValue).Selected = True
}
else
{
if (nsertIfNotExists=true)
{
//insert item
ddl.Insert(0, new ListItem(textOfItem,valueToSelect))

}
}

Open in new window

0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
High user turnover can cause old/redundant user data to consume valuable space. UserResourceCleanup was developed to address this by automatically deleting user folders when the user account is deleted.
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
Integration Management Part 2

879 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question