ListView中获取ClientID的一个小问题

今天在VS2010中使用ListView控件的时候,遇到了这么一个问题:在ItemCreated事件中无法找到在ListView中的控件的ClientID,准确说是得到一个错误的ClientID

引发事件的代码如下:

protected void ListView1_ItemCreated(object sender, ListViewItemEventArgs e)
{
     if (e.Item.ItemType == ListViewItemType.InsertItem)
     {
          TextBox txt_name = (TextBox)e.Item.FindControl("nameTextBox");
          txt_name.Attributes["haha"] = txt_name.ClientID;
     }
}
结果得到的ClientID就是错误的,它会在前面加个ctrl3_,但真实的ClientID是ListView1_nameTextBox

r_Html.jpg

解决这个问题方案是可以在ItemDataBound事件中获取正确的ClientID值或者在PreRender事件中获取客户端ID也可以,具体解决方案和原因参看:http://connect.microsoft.com/VisualStudio/feedback/details/328680/problem-accessing-controls-clientid-on-asp-net-listviews-itemcreated

 

由于我的界面InsertItem类型是没有数据绑定的,所以我采用在PreRender事件中获取的方法:

protected void ListView1_PreRender(object sender, EventArgs e)
{
     TextBox txt_age =(TextBox)FindControl("ageTextBox", ListView1.Controls);
     if(txt_age!=null)
          txt_age.Attributes["haha"] = txt_age.ClientID;
}
其中FindControl为自定义静态函数:

public static Control FindControl(string controlId, ControlCollection controls) {
foreach (Control control in controls) {
    if (control.ID == controlId)
     return control;
    if (control.HasControls()) {
     Control nestedControl = FindControl(controlId, control.Controls);
     if (nestedControl != null)
        return nestedControl;
     }
}
return null;
}
这样,结果就正确了。

r_Html2.jpg

 

转载于:https://www.cnblogs.com/heqichang/archive/2010/09/17/1829617.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值