Unable to refund items in the list box

I have been working on a code snippet to retrieve a list of items from a listbox. The listbox can contain any number of 10-digit numbers in multiple rows. However, when I run the code, the "NPIListBox.Items.Count" function only returns a count of 1, even when there are 3 items in the list box. Can anyone help me understand why this discrepancy occurs? My main objective is to store all listbox items in a session so that I can access the values on another page. Thank you!

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If IsPostBack Then
           PopulateListBox()
    End If

End Sub

Protected Sub cmdNext_Click(sender As Object, e As System.Web.UI.ImageClickEventArgs) Handles cmdNext.Click
    Dim n As Integer = NPIListbox.Items.Count
    Dim arr As String() = New String(n - 1) {}
    For i As Integer = 0 To arr.Length - 1
        arr(i) = NPIListbox.Items(i).ToString.Substring(NPIListbox.Items(i).ToString.Length - 10)
    Next
    Session("arr") = arr

    Response.Redirect("~/frmDescription.aspx")
End Sub

Private Sub PopulateListBox()

    If DoctorNameTextBox.Text = "" Then

    Else
        ' Get value from text box
        Dim textBoxValue As String = Me.DoctorNameTextBox.Text

        ' Create new item to add to list box
        Dim newItem As New ListItem(textBoxValue)

        ' Add item to list box and set selected index
        NPIListbox.Items.Add(newItem)
        NPIListbox.SelectedIndex = NPIListbox.Items.Count - 1


    End If

The list box is populated using the following javascript code


<script language="javascript" type="text/javascript">
  function getSelected(source, eventArgs) {
      var s = $get("<%=DoctorNameTextBox.ClientID %>").value;

      var opt = document.createElement("option");
      opt.text = s.substring(s.length - 10);
      opt.value = s.substring(s.length - 10);

      document.getElementById('<%= NPIListbox.ClientID %>').options.add(opt);

  }

Answer №1

By dynamically adding options using JavaScript, the server is not aware of this change. Therefore, when posting the values back, the original count (1) is retrieved because the newly added options did not exist at runtime.

To access the newly added values, an alternative method must be used. One approach is to add them to a hidden field with runat='server' and retrieve the values from there.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switch out image with Jquery when hovering, and revert to default on mouse out

Despite the numerous times this question has been asked, I am struggling to find a solution that fits my specific case. Let's dive into it. My navigation setup involves using Bootstrap nav pills to navigate through content. The structure looks like t ...

AngularJS textbox failing to recognize line breaks as expected

I am struggling with the following HTML code: <div class="form-group"> <div class="input-group col-sm-12"> <label for="" class="control-label">Comments</label> ...

Automatically injecting dependencies in Aurelia using Typescript

Recently, I started working with Typescript and Aurelia framework. Currently, I am facing an issue while trying to implement the @autoinject decorator in a VS2015 ASP.NET MVC 6 project. Below is the code snippet I am using: import {autoinject} from "aure ...

What is preventing Backbone from triggering a basic route [and executing its related function]?

Presenting My Router: var MyRouter = Backbone.Router.extend({ initialize: function(){ Backbone.history.start({ pushState:true }); }, routes: { 'hello' : 'sayHello' }, sayHello: function(){ al ...

Creating interactive JavaScript elements that can be moved around within a container

I recently faced a challenge while attempting to make draggable elements within a div. The issue arose when I realized that I couldn't figure out how to drag each element individually without affecting the others. My current code only allows for handl ...

Struggling for hours with a nested React component that refuses to render

I'm new to the world of react and javascript development and currently encountering an issue with nesting a component. While the Home component is displaying correctly, the testComp is not appearing as expected. I'm feeling quite stuck and would ...

Exploring jasmine-node: unraveling the mysteries of errors

As I embark on my journey to learn JavaScript, I decided to tackle some exercises on exercism.io. This platform provides pre-written tests that need to be passed. While things were going smoothly initially, I hit a roadblock with the latest exercise where ...

Error encountered in jquery.d.ts file: Unresolved syntax issue

I am currently in the process of transitioning my jQuery project into a Typescript project. I encountered an issue when attempting to include the jQuery typings from the DefinitelyTyped Github by using the following method: ///<reference path="../../ty ...

Error encountered with modalpopupextender validation functionality

Is there a way to prevent the submit button on the ModalPopUpExtender from causing a postback when validation errors occur? I am looking for a solution to implement validation on the ModalPopUpExtender in order to avoid postback when errors are present an ...

Having trouble getting my list items to display on individual lines within the foreach loop. It just doesn't seem to be working as expected

In the event listener, I need to ensure that my list items within the forEach loop are not displaying on separate lines. This issue is causing a problem in a lengthy section of code. The goal is to update questions when an answer is clicked from a list. B ...

Include a nonce attribute in the automatically generated WebForms script

When integrating the CSP header on my website, I am encountering issues with the automatically generated postback JavaScript that webforms inserts into the page: <script type="text/javascript"> //<![CDATA[ var theForm = document.forms[&a ...

How can I create a JSON string that exactly matches the data source needed for a pie chart? Any tips

received JSON string: "{Date:'15/05/2015',y:'6'}, {Date:'01/08/2015',y:'6'}, {Date:'02/08/2015',y:'6'}, {Date:'08/08/2015',y:'72'}, {Date:'09/08/2015',y:&apo ...

Preserving Row Selection in ASP.NET GridView Component

Situation: My current project involves a page containing a GridView control inside of an update panel, utilizing a SqlDataSource. I have set up a timer to refresh the GridView every X seconds. Typically, with each update, 4-5 new rows are added to the Grid ...

What could be causing this Javascript Array() to generate an array containing just a single element?

In my next js app, I have the following function: export async function getServerSideProps(ctx) { const campaign = campaignInstance(ctx.params.address); const requestCount = await campaign.methods.getRequestsCount().call(); console.log(req ...

What is the best way to preserve leading spaces in an ASP.NET textbox?

I encountered an issue with a text-box web control that automatically removes leading spaces from its content. This results in the text not matching the user's initial input if they added a space at the beginning. Is there a way to turn off this featu ...

The context does not contain label1: asp.net C#

In my current ASP.NET project, I am working with C# to create two integer variables, m = 5 and s = 2, and assigning datetime objects: minutes to m and seconds to s. I am then concatenating each of them to a string variable, str, and performing increments ...

Choose a looping function in React JS that iterates over an array of objects

I have an array of objects let arr = [0: {received: "Return Received", approved: "Approved", rejected: "Rejected"} 1: {authorized: "Authorized", received: "Return Received"}} I am looking to populate a < ...

Utilizing AngularJS and ADAL.JS to Define Resource ID (Audience)

Is there a way to utilize adal.js within AngularJS to obtain a bearer token for the audience https://management.azure.com through JavaScript? I have created a client application in Azure AD and configured its permissions to allow access to the "Windows Az ...

A guide on implementing a confirmation box with jquery confirm plugin for form submission

After submitting a form, I want to display a confirmation message without using the typical method of "return confirm("Are You Sure?")". I decided to utilize JQuery Confirm in this way: @using (@Html.BeginForm("SubmitTest", "HydrostaticReception", FormMe ...

The process of making a pop-up modal instead of just relying on alerts

Attempting to change from using an alert to a pop-up with a simple if statement, but encountering some issues. Here is the current code: if(values == ''){ $('body').css('cursor','auto'); alert("Blah Blah..." ...