今天在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;
}
}
解决这个问题方案是可以在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;
}
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;
}