Solved

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

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

778 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