Thursday, November 12, 2009

Multiple selection in listbox

Most of the people find difficulty to save multiple data into database while selecting a listbox.
That’s possible by implementing the following method.

For example in an application there are several languages to be selected. The user can select any number of language from the list box.

We can add them into an collection called objColl

List<LanguageInfo> objColl = new List<LanguageInfo>();
for (int intCount = 0; intCount < lstLanguages.Items.Count; intCount++)
LanguageInfo objLanguages = new LanguageInfo();
if (lstLanguages.Items[intCount].Selected == true)
objLanguages.LanguageID = Convert.ToInt32(lstLanguages.Items[intCount].Value);

The next thing we can do is, we can append a comma to each languageid
IEnumerator<LanguageInfo> ILanguages = Languages.GetEnumerator();
while (ILanguages.MoveNext())
(Here Languages is the list that we passed to update in database)
In back-end just have a split method to split the data by comma. And it can be updated to the database.
CREATE function [dbo].[fn_Split](
@Languages nvarchar (1000),
@CustomerId int,
@Delimiter nvarchar (10)
returns @ValueTable table ([LanguageID] INT, [ProgramInfoId] INT)
declare @NextString nvarchar(4000)
declare @Pos int
declare @NextPos int
declare @CommaCheck nvarchar(1)

set @NextString = ''
set @CommaCheck = right(@Languages,1)

set @Languages = @Languages + @Delimiter

set @Pos = charindex(@Delimiter,@Languages)
set @NextPos = 1

while (@pos <> 0)
set @NextString = substring(@Languages,1,@Pos - 1)

insert into @ValueTable ( [LanguageID], [CustomerId]) Values (@CustomerId, @NextString)

set @Languages = substring(@Languages,@pos +1,len(@Languages))

set @NextPos = @Pos
set @pos = charindex(@Delimiter,@Languages)


1 comment:

  1. hi friend,
    Thanks to post this article at here..
    that help me alot..
    i have one suggestiation at here. we can replace for loop with foreach loop and we can get the element from the listbox..
    for example

    foreach (listitem lstItem in listbox.items)
    if (lstitem.selected == true)
    // do your stuff at here.

    Jayesh L



Obstacles are those frightful things you see when you take your eyes off your goal.------> by Henry Ford