Puskarkc007
Puskarkc007

Reputation: 174

How to Store List of selected value from multiselect dropdown list in array in asp.net?

I used Bootstrap multiselect dropdown item, in which if I select many values it only select the first values, whats wrong in my code logic.

Asp dropdown list

<asp:dropdownlist  Width="320px" id="drplstGetDb" runat="server"  multiple="Multiple">  </asp:dropdownlist>

Javascript to enable multiple check feature from bootstrap.

$(function() {
    $('[id*=drplstGetDb]').multiselect({
        includeSelectAllOption: true
    });
});

C# Code to store in array.

int[] stopWordArray = new int[drplstGetDb.Items.Count];

foreach(ListItem listItem in drplstGetDb.Items) {
    if (listItem.Selected) {
        int i = 0;
        stopWordArray[i] = Convert.ToInt32(drplstGetDb.Items[i].Value.ToString());
        i++;
    }
}

I am only getting first checked value in array, If I don't use this if if (listItem.Selected) I can Store all values in array. Can anyone suggest about this error,, Specially with Selected Logic. or Alternative to this..

Upvotes: 1

Views: 3163

Answers (1)

jraffdev
jraffdev

Reputation: 46

Because you are setting

int i = 0 

inside the loop, you are setting the first array element of stopWordArray ALL THE TIME, no matter what. Move the

int i = 0 

to the outside of the foreach and you should have better luck there.

Try this

int[] stopWordArray = new int[drplstGetDb.Items.Count];
int i = 0;
foreach(ListItem listItem in drplstGetDb.Items)
{
    if (listItem.Selected)
    {
        stopWordArray[i] = Convert.ToInt32(listItem.Value.ToString()); //something like this
        i++;
    }
}

Maybe even easier would be to get rid of the int array and use a list

List<int> stopWordArray = new List<int>();

foreach (ListItem listItem in drplstGetDb.Items)
 {
     if (listItem.Selected)
      {
          stopWordArray.Add(Convert.ToInt32(listItem.Value.ToString()));
      }
 }

Upvotes: 2

Related Questions