Solved

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

Posted on 2015-02-05
1
278 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 500 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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

708 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now