Dynamically create checkbox using repeater control and read the selected values in VB.Net

In this article I am going to discuss how to dynamically generate a checkbox using repeater.One should be able to use similar approach to dynamically load any  control.Its simple to create a repeater dynamically .It gets  a bit tricky when it comes to reading the values  from the checkboxes to get the selection .

Please read the article in its entirety to know it all .

In the design view create your repeater and bind a checkbox item to it .This is pretty simple (see the code sample below)

image

In the code behind under page load event ,bind the repeater to a source(see code sample below).

Ideally you could bind it to any event of your choice depending upon you case ,but I did it in page load event

image

Datasource literatureReqd  is an array string .The number of items in the array define the number of checkboxes to be created dynamically .I am using the string in the array as label for checkbox (which you will see in the code sample  later).

For example, if my array is under

Dim literatureReqd As string()={“test1,test2,test3”},it will create 3 checkboxes with labels test1 ,test2 and test3 respectively .

 

Below is the code for ItemDatabound method for the repeater

image

 

Now comes the interesting part when you have to read the values of the selection from the checkboxes .In my case I had to read those value on button click and assign them as property to an object which was then passed on for further processing (see the code below )

image

As seen in the code above , below is the sequence of actions:

a)Loop  through each repeaterItems  -Ln 30

b)Find the checkbox using repeater.FindControl() method  –Ln 32

c)If the item is not null then get the required values and assign them to my object –Ln 34 to Ln37

 

I would like to thank my colleague Ken as well who helped be debug the tricky bit .

Happy coding Smile

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s