Looping Through RadioButtonLists

Published on
-
1 min read

At the moment I am working on a Survey that contains tonnes of RadioButtonList controls that users will use to respond to the numerous questions I have on the website. All was going well until I thought about how I would find a quick and efficient way to enter all the RadioButtonList entries into my SQL database without having to do the following:

_rblBLL.InsertResults(1, rblist1.SelectedValue);
_rblBLL.InsertResults(2, rblist2.SelectedValue);
_rblBLL.InsertResults(3, rblist3.SelectedValue);
...
...
...
...

(InserResults() is my BLL function)

As you can see above, this is indeed a long winded way of inserting all my RadioButtonList entries to the database.

But I found a better way by using the FindControl() method:

for (int i=1; i < questionNo; i++)
{      
    RadioButtonList rbl = (RadioButtonList)this.FindControl("rblist" + i);

    if(rbl != null)
    {
         _rblBLL.InsertResults(i, rbl.SelectedValue);
    }
} 

As you can see, I created a for loop that will iterate through all the RadioButtonLists by incrementing the end value of RadioButtonList ID. So you will have to adopt a naming convention that has a number at the end as shown I have used above.

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. I do get inundated with messages regarding my posts via LinkedIn and leaving a comment below is a better place to have an open discussion. Your comment will not only help others, but also myself.