0
votes

I have a ListBox which is populated dynamically from a database in the code behind. I have another button and when i click the button, the button click event will get the all the selected listitem and insert the list item text to the database. I set AutoPostBack as false and EnableViewState is true in the listbox property

The problem is when i click the button , it only see 1 selected item even i select multiple items.Here are the codes. I appreciate your help. I spend 1 day on this issue and not getting anywhere.

protected void Page_Load(object sender, EventArgs e)
{  
        if (!IsPostBack)
        {    
            loadrdlist();
        }  
} 

protected void loadrdlist()
{
         ((ListBox)TestFormView.FindControl("ListBoxB")).Items.Clear();

        foreach (FailureTempRD rd in FailureTempRD.SelectFailureTempRD())
            ((ListBox)TestFormView.FindControl("ListBoxB")).Items.Add(new ListItem(rd.ReferenceDesignator, rd.ReferenceDesignator)); 
}

protected void btn_AddRD_Click(object sender, EventArgs e)
{
    foreach (ListItem rd in ((ListBox)TestFormView.FindControl("ListBoxB")).Items) //This is where it only see 1 selected item
     {
        if (rd.Selected == true) 
           //put selected item to database
        }
    }
}

Here are both listbox and button

<asp:ListBox ID="ListBoxB" runat="server" SelectionMode="Multiple" ></asp:ListBox>
<asp:Button ID="btn_AddRD" runat="server" CausesValidation="False"  onclick= "btn_AddRD_Click" Text="Add" />

Update : I figure why. When i load the listitem, i need to add ID as listitem value. So change the following code. I test few times and it works as intend.

 ((ListBox)TestFormView.FindControl("ListBoxB")).Items.Add(new ListItem(rd.ReferenceDesignator, rd.ReferenceDesignator)); 

To

 ((ListBox)TestFormView.FindControl("ListBoxB")).Items.Add(new ListItem(rd.ReferenceDesignator, rd.ID));
1
Is ListBox inside a Gridview??Nalaka526
Sorry , the list box and button are both in formview. I edit my post and the formview is in Insert Mode.windforceus

1 Answers

0
votes

Try using the GetSelectedIndices Method.

From above link:

Use the GetSelectedIndices method to identify or access the selected items in the ListBox control. Each element in the returned array represents the index for a selected list item. You can use the index values to access the items in the Items collection.