Repeater and Checkboxs

K

Kevin Humphreys

Hi,
Can someone give me a code look at how I can create a Dynamic Checkbox
within a repeater using VB.NET?

Thanks,
Kevin.
 
V

Velislav

Ok, here's a quick sample:

this is a snippet out of the aspx page:

<table>
<asp:Repeater runat="server" ID="myRepeater">
<ItemTemplate>
<tr>
<td>
<asp:CheckBox runat="server" ID="myCheckBox" />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
<asp:Button ID="doPostBack" runat="server" Text="Do PostBack" />

in the code, I show how to bind the checkboxes and then access whatever
their values are on postback:

Protected Sub myRepeater_ItemDataBound(ByVal sender As Object, ByVal e
As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles
myRepeater.ItemDataBound
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType =
ListItemType.AlternatingItem) Then
Dim myCheckBox As CheckBox =
CType(e.Item.FindControl("myCheckBox"), CheckBox)
myCheckBox.Checked = CBool(e.Item.DataItem)
End If
End Sub

Public Overrides Sub DataBind()
Dim checkBoxValues(2) As Boolean
checkBoxValues(0) = True
checkBoxValues(1) = False
checkBoxValues(2) = True
myRepeater.DataSource = checkBoxValues
MyBase.DataBind()
End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
If (Not IsPostBack) Then
DataBind()
End If
End Sub

Protected Sub doPostBack_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles doPostBack.Click
Dim index As Integer
While (index < myRepeater.Items.Count)
Dim myCheckBox As CheckBox =
CType(myRepeater.Items(index).FindControl("myCheckBox"), CheckBox)
Dim output As LiteralControl = New
LiteralControl(String.Format("Item index: {0}; CheckBox Checked:
{1};<br>", index, myCheckBox.Checked.ToString()))
Page.Controls.Add(output)
index += 1
End While
End Sub
 
V

Velislav

ugh.... sorry, if you want to create the CheckBox programatically, then
all you do is create it in the ItemCreated event handler of the
repeater:

Protected Sub myRepeater_ItemCreated(ByVal sender As Object, ByVal
e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles
myRepeater.ItemCreated
Dim myDynamicCheckBox As CheckBox = New CheckBox()
myDynamicCheckBox.ID = "myDynamicCheckBox"
myDynamicCheckBox.Checked = False
e.Item.Controls.Add(myDynamicCheckBox)
End Sub

then access it the same way as the previous way, just use the correct
ID (ie. myDynamicCheckBox) in as the parameter of the FindControl call.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,085
Messages
2,570,597
Members
47,218
Latest member
GracieDebo

Latest Threads

Top