Getting Values from Textbox in Nested ListView Controls

A few days ago, I was given a task to build a simple web application to maintain and display the results from an upcoming local election. Since this was supposed to be a very simple election, using a hand counted paper ballot, I didn’t think it would be that difficult.

I decided to use the ListView control that I had recently learned of  (Yes, I am very behind). The ListView control made it very easy to build both the data output, and the input form, by binding a datasource to the parent control with a record for each race being run. I then bound a secondary datasource to a nested ListView control for each record to display the candidates for each race.

Here is a screen capture of the simple input form I built.

Paper Ballot Maintenance Screen

The front-end code example: ListView-front end Code Example

 

There are a lot of different ways to handle this code, but this was a rush job, and needed to get done quickly.

The plan was to have the Elections folks enter the votes received data as they get it from polling locations on election night after the polls close,  and then update the datasource as needed.

This sounded simple, until I tried to get the data from the text boxes in the nested ListView. Then things got complicated. And while I searched and searched on-line for a solution, I didn’t find one that fit my particular circumstances.

I started out looping over the top level ListView, and getting the values from each of the drop-down fields. This went smoothly. But I quickly found that I didn’t have access to the text box fields, as they were in a child object. The solution I finally came up with is the following excerpt from the code behind file: ListView-codebehind Code Example

The trick turned out to be to find out how many items are in the ListView, start a for loop going the same number of times as items in the ListView. At each iteration of the loop, get the information you need, and load it into whatever you need to interact with the data. In my case I am loading it into an object for later processing.

In addition, look for a child ListView control. In this case, I put it into a try/catch, so I could proceed even if one isn’t present. Instantiate a new ListView object in the code behind, and load the child control into it. You now have access to all of the data present in that child ListView control. Repeat the process from above: loop over the ListView object, now looking for your text boxes. Load each one of them into a new TextBox object, and you have the data.

It seems cumbersome, and probably is. Let me know what you think, or if you have a better way of handling this. I am sure that there is a more elegant way to accomplish this, and I would love to know about it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.