今天要给repeater做上一个checkbox,然后能做到圈选反选,本来很简单的事,但是我发现了findcontrol方法的一个好的优点。
前台绑定方法如下:
后台代码如下:
foreach (Control c in this.Repeater1.Controls)
{
CheckBox check = (CheckBox)c.FindControl("ch");
if (check != null)
{
check.Checked = true;
}
}
好像细看没什么神奇,但是,从html代码中,你看到repeater生成的html代码如下:
地球人都知道服务器端的id到了客户端就极有可能在asp.net生成控件树的时候被asp.net自动重命名,为的防止一个页面多个重复id,那为什么在回发的时候后台又能够通过findcontrol("ch")来获取到呢?这就是asp.net为我们作的工作了。
顺便说说3种获得repeater中的checkbox 的方法:
foreach( RepeaterItem item in this.Repeater1.Items )
{
HtmlInputCheckBox check = (HtmlInputCheckBox)item.FindControl("cbDelete1");
if( check != null )
{
check.Checked = true;
}
}
for (int i=0;i<this.Repeater1.Items.Count;i++)
{
HtmlInputCheckBox check = (HtmlInputCheckBox)this.Repeater1.Items[i].FindControl("cbDelete1");
if( check != null )
{
check.Checked = true;
}
}
foreach (Control c in this.Repeater1.Controls)
{
HtmlInputCheckBox check = (HtmlInputCheckBox)c.FindControl("cbDelete1");
if( check != null )
{
check.Checked = true;
}
}
Dim chkSelect As CheckBox
Dim lblProductID As Label
For Each item As RepeaterItem In Repeater1.Items
chkSelect = DirectCast(item.FindControl("ch"), CheckBox)
If chkSelect IsNot Nothing AndAlso chkSelect.Checked = True Then
lblProductID = TryCast(item.FindControl("Label8"), Label)
Response.Write("
" & lblProductID.Text)